numbers = 1..10
print numbers.map {|x| x*x}
# I want to do:
square = {|x| x*x}
print 开发者_C百科numbers.map square
Because the syntax is more concise. I there a way to do this without having to use def
+ end
?
square = proc {|x| x**2 }
print number.map(&square)
You cannot assign a block to a variable because a block isn't really an object per se.
What you can do, is assign a Proc
object to a variable, and then convert that to a block using the &
unary prefix operator:
numbers = 1..10
print numbers.map {|x| x * x }
square = -> x { x * x }
print numbers.map &square
numbers = 1..10
square = lambda{|x| x*x }
numbers.map &square
精彩评论