开发者

How can I define/name a block in Ruby?

开发者 https://www.devze.com 2023-02-16 19:55 出处:网络
numbers = 1..10 print numbers.map {|x| x*x} # I want to do: square = {|x| x*x} print 开发者_C百科numbers.map square
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
0

精彩评论

暂无评论...
验证码 换一张
取 消