# 宣告1
proc1 = Proc.new do |x|
puts x
end
# 宣告2
proc2 = proc do |x|
puts x
end
# Proc#call
proc1.call("hello world") # hello world
# Proc#[]
proc2["hey, how are you?"] # hey, how are you?
Feature of Closure
可透過Proc 達到closure 的目的
1234567891011
def counter
c=0
Proc.new do c += 1 end
end
c1 = counter
c2 = counter
c1.call # 1
c1.call # 2
c2.call # 1
defpower_of(n)lambdado|x|returnx**nendendcube=power_of(3)cube.call(5)# 125# using Procdefpower_of(n)Proc.newdo|x|returnx**nendendcube=power_of(3)cube.call(5)# LocalJumpError
defmy_method_no_argputs"warm up 1"yieldenddefmy_method_with_argputs"warm up 2"# yield('james')yield(%W(a b))endmy_method_no_argdoputs"running alone"endmy_method_with_argdo|friends|# puts friends.classiffriends.class==Stringputs"running with #{friends}"elsefriends.eachdo|friend|puts"running with #{friend}"endendend