如何将参数传递给数组。地图捷径?(复制)

时间:2021-12-16 21:24:56

This question already has an answer here:

这个问题已经有了答案:

Given the following array a:

给定以下数组a:

a = [1, 2, 3, 4, 5]  

How do I do:

我怎么做:

a.map { |num| num + 1 }  

using the short notation:

使用短的符号:

a.map(&:+ 1)  

or:

或者:

a.map(&:+ 2)  

where 1 and 2 are the arguments?

参数1和2在哪里?

4 个解决方案

#1


34  

You can't do it like this. The & operator is for turning symbols into procs.

你不能这样做。&运算符用于将符号转换为procs。

a = [1, 2, 3, 4, 5]  
puts a.map(&:to_s) # prints array of strings
puts a.map(&:to_s2) # error, no such method `to_s2`.

& is a shorthand for to_proc:

&是to_proc的简写:

def to_proc
  proc { |obj, *args| obj.send(self, *args) }
end

It creates and returns new proc. As you see, you can't pass any parameters to this method. You can only call the generated proc.

它创建并返回新的proc。您只能调用生成的proc。

#2


39  

In this case you can do

在这种情况下你可以这么做

a.map(&1.method(:+))

But only because 1 + x is usually the same as x + 1.

只是因为1 + x通常等于x + 1。

Here is a discussion of this practice in a performance context.

以下是在性能上下文中对这种实践的讨论。

#3


25  

You cannot do it with map. But look at Facets' Enumerable#map_send:

你不能用地图。但是看看facet的可枚举的#map_send:

require 'facets'
[1, 2, 3].map_send(:+, 1)
#=> [2, 3, 4]

Writing your own implementation is pretty straightforward:

编写自己的实现非常简单:

module Enumerable
  def map_send(*args)
    map { |obj| obj.send(*args) }
  end
end

#4


0  

If you really need that you can use Ampex library, but I don't know if it is still maintained.

如果您确实需要的话,可以使用Ampex库,但是我不知道它是否仍然被维护。

#1


34  

You can't do it like this. The & operator is for turning symbols into procs.

你不能这样做。&运算符用于将符号转换为procs。

a = [1, 2, 3, 4, 5]  
puts a.map(&:to_s) # prints array of strings
puts a.map(&:to_s2) # error, no such method `to_s2`.

& is a shorthand for to_proc:

&是to_proc的简写:

def to_proc
  proc { |obj, *args| obj.send(self, *args) }
end

It creates and returns new proc. As you see, you can't pass any parameters to this method. You can only call the generated proc.

它创建并返回新的proc。您只能调用生成的proc。

#2


39  

In this case you can do

在这种情况下你可以这么做

a.map(&1.method(:+))

But only because 1 + x is usually the same as x + 1.

只是因为1 + x通常等于x + 1。

Here is a discussion of this practice in a performance context.

以下是在性能上下文中对这种实践的讨论。

#3


25  

You cannot do it with map. But look at Facets' Enumerable#map_send:

你不能用地图。但是看看facet的可枚举的#map_send:

require 'facets'
[1, 2, 3].map_send(:+, 1)
#=> [2, 3, 4]

Writing your own implementation is pretty straightforward:

编写自己的实现非常简单:

module Enumerable
  def map_send(*args)
    map { |obj| obj.send(*args) }
  end
end

#4


0  

If you really need that you can use Ampex library, but I don't know if it is still maintained.

如果您确实需要的话,可以使用Ampex库,但是我不知道它是否仍然被维护。