5

如何在 Ruby 中按名称传递函数?(我只使用 Ruby 几个小时,所以我还在搞清楚。)

nums = [1, 2, 3, 4]

# This works, but is more verbose than I'd like    
nums.each do |i|
  puts i
end

# In JS, I could just do something like:
# nums.forEach(console.log)

# In F#, it would be something like:
# List.iter nums (printf "%A")

# In Ruby, I wish I could do something like:
nums.each puts

可以在 Ruby 中同样简洁地完成吗?我可以只按名称引用函数而不是使用块吗?

人们投票结束:你能解释为什么这不是一个真正的问题吗?

4

3 回答 3

6

You can do the following:

nums = [1, 2, 3, 4]
nums.each(&method(:puts))

This article has a good explanation of the differences between procs, blocks, and lambdas in Ruby.

于 2012-12-10T21:33:43.517 回答
3

Can I just reference the function by name instead of wrapping it in a block?

You aren't 'wrapping' it -- the block is the function.

If brevity is a concern, you can use brackets instead of do..end:

nums.each {|i| puts i}
于 2012-12-10T21:34:46.073 回答
0

不是开箱即用的,尽管您可以使用method

def invoke(enum, meth)
  enum.each { |e| method(meth).call(e) }
end

我更喜欢把它包成一个猴子补丁Enumerable

还有其他方法可以解决这个问题;这是一种蛮力。

于 2012-12-10T21:37:05.550 回答