简体   繁体   English

如何在数组上映射方法?

[英]How do I map a method over an array?

Let's say I have a method (which is actually a helper): 假设我有一个方法(实际上是一个助手):

def f(x)  
  x + 1  
end

What I want to do is to map it over an enumerable like so: 我想要做的是将它映射为一个可枚举的对象,如下所示:

(1..10).map &f

It's obviously doesn't work raising ArgumentError: wrong number of arguments (0 for 1) error. 引发ArgumentError: wrong number of arguments (0 for 1)显然不起作用ArgumentError: wrong number of arguments (0 for 1)错误。 I know that I can call this method in block like so: 我知道我可以像这样在块中调用此方法:

(1..10).map {|x| f x }

But it doesn't look like an elegant solution to me. 但这对我来说似乎不是一个优雅的解决方案。 What else can be done about it? 还有什么可以做的呢?

您可以使用:

(1..10).map(&method(:f))

First of all, I don't see any inelegance in this 首先,我没有看到任何优雅

(1..10).map {|x| f x }

Normally, you should be using it. 通常,您应该使用它。 But, under special circumstances, a special form is available (you need to call a method on an object and that method doesn't accept arguments). 但是,在特殊情况下,可以使用一种特殊形式(您需要在对象上调用一个方法,并且该方法不接受参数)。

class Fixnum
  def f
    self + 1
  end
end

(1..10).map(&:f)

Between these two approaches, I'd take the first one any day. 在这两种方法之间,我会选择第一天。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM