如何在Ruby中定义/命名块?

8 ruby

numbers = 1..10
print numbers.map {|x| x*x}

# I want to do:
square = {|x| x*x}
print numbers.map square
Run Code Online (Sandbox Code Playgroud)

因为语法更简洁.我有办法做到这一点,而不必使用def+ end

Gui*_*nal 14

square = proc {|x| x**2 }
print number.map(&square)
Run Code Online (Sandbox Code Playgroud)


Jör*_*tag 8

您不能将块分配给变量,因为块本身并不是对象.

可以做的是将Proc对象分配给变量,然后使用&一元前缀运算符将其转换为块:

numbers = 1..10
print numbers.map {|x| x * x }

square = -> x { x * x }
print numbers.map &square
Run Code Online (Sandbox Code Playgroud)

  • 对于任何编辑我的答案的人,以及批准该编辑的两个人:如果你不知道你在做什么,那就不要.我对修复错误的人没有任何问题,但是*引入*它们并不合适.我的代码完美无缺,你的代码不仅无法工作,甚至无法解析*. (4认同)