ruby 如何传递函数而不是块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13945503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:36:30  来源:igfitidea点击:

How to pass a function instead of a block

rubyfunctional-programming

提问by Hanfei Sun

Possible Duplicate:
Shorter way to pass every element of an array to a function

可能的重复:
将数组的每个元素传递给函数的更短方法

I know this will work:

我知道这会起作用:

def inc(a)
  a+1
end
[1,2,3].map{|a| inc a}

but in Python, I just need to write:

但在 Python 中,我只需要写:

map(inc, [1,2,3])

or

或者

[inc(x) for x in [1,2,3])

I was wondering whether I can skip the steps of making a block in Ruby, and did this:

我想知道是否可以跳过在 Ruby 中创建块的步骤,然后这样做:

[1,2,3].map inc
# => ArgumentError: wrong number of arguments (0 for 1)
# from (irb):19:in `inc'

Does anyone have ideas about how to do this?

有没有人有关于如何做到这一点的想法?

回答by Platinum Azure

According to "Passing Methods like Blocks in Ruby", you can pass a method as a block like so:

根据“在 Ruby 中传递类似块的方法”,您可以将方法作为块传递,如下所示:

p [1,2,3].map(&method(:inc))

Don't know if that's much better than rolling your own block, honestly.

老实说,不知道这是否比滚动自己的块要好得多。

If your method is defined on the class of the objects you're using, you could do this:

如果您的方法是在您使用的对象的类上定义的,您可以这样做:

# Adding inc to the Integer class in order to relate to the original post.
class Integer
  def inc
    self + 1
  end
end

p [1,2,3].map(&:inc)

In that case, Ruby will interpret the symbol as an instance method name and attempt to call the method on that object.

在这种情况下,Ruby 会将符号解释为实例方法名称并尝试调用该对象上的方法。



The reason you can pass a function name as a first-class object in Python, but not in Ruby, is because Ruby allows you to call a method with zero arguments without parentheses. Python's grammar, since it requires the parentheses, prevents any possible ambiguity between passing in a function name and calling a function with no arguments.

您可以在 Python 中将函数名称作为第一类对象传递,而在 Ruby 中则不能,这是因为 Ruby 允许您调用带有零参数且不带括号的方法。Python 的语法,因为它需要括号,所以可以防止在传入函数名和调用不带参数的函数之间出现任何可能的歧义。

回答by oldergod

Does not answer your question but if you really just want to increment all your variables, you have Integer#next

不回答你的问题,但如果你真的只想增加你的所有变量,你有 Integer#next

4.next
#=> 5

[1,2,3].map(&:next)
#=> [2, 3, 4]

回答by unnitallman

def inc(a)
  a + 1 
end

p [1,2,3].map{|a| inc a}