defargs(code)one,two=1,2code.call(one,two)endargs(Proc.new{|a,b,c|puts"Give me a #{a} and a #{b} and a #{c.class}"})# => Give me a 1 and a 2 and a NilClassargs(lambda{|a,b,c|puts"Give me a #{a} and a #{b} and a #{c.class}"})# *.rb:8: ArgumentError: wrong number of arguments (2 for 3) (ArgumentError)
defgeneric_return(code)one,two=1,2three,four=code.call(one,two)return"Give me a #{three} and a #{four}"endputsgeneric_return(lambda{|x,y|returnx+2,y+2})putsgeneric_return(Proc.new{|x,y|returnx+2,y+2})putsgeneric_return(Proc.new{|x,y|x+2;y+2})putsgeneric_return(Proc.new{|x,y|[x+2,y+2]})# => Give me a 3 and a 4# => *.rb:9: unexpected return (LocalJumpError)# => Give me a 4 and a# => Give me a 3 and a 4# proc 需再用 array 包覆起來
classPeopleattr_reader:namedefinitialize(name)@name=nameenddefcoding(language)puts"like #{language}"endenda=People.new('leon')a.method(:coding).class#=> Methoda.method(:coding).call('ruby')#=> like ruby
# wants a proc, a lambda, AND a blockdefthree_ways(proc,lambda,&block)proc.calllambda.callyield# like block.callputs"#{proc.inspect}#{lambda.inspect}#{block.inspect}"endanonymous=Proc.new{puts"I'm a Proc for sure."}nameless=lambda{puts"But what about me?"}three_ways(anonymous,nameless)doputs"I'm a block, but could it be???"end#=> I'm a Proc for sure.#=> But what about me?#=> I'm a block, but could it be???#=> #<Proc:0x00089d64> #<Proc:0x00089c74> #<Proc:0x00089b34>
Style
用 ->(){} 而不是 lambda{}
123456789101112131415161718
# badl=lambda{|a,b|a+b}l.call(1,2)# correct, but looks extremely awkwardl=->(a,b)dotmp=a*7tmp*b/50end# goodl=->(a,b){a+b}l.call(1,2)l=lambdado|a,b|tmp=a*7tmp*b/50end
用 proc 而不是 Proc.new
12345
# badp=Proc.new{|n|putsn}# goodp=proc{|n|putsn}
用 proc.call() 而不是 proc[] 或 proc.()
1234567891011
# bad - looks similar to Enumeration accessl=->(v){putsv}l[1]# also bad - uncommon syntaxl=->(v){putsv}l.(1)# goodl=->(v){putsv}l.call(1)