如何将参数传递给 array.map 快捷方式? [英] How do I pass an argument to array.map short cut?
本文介绍了如何将参数传递给 array.map 快捷方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定以下数组a
:
a = [1, 2, 3, 4, 5]
我该怎么做:
a.map { |num| num + 1 }
使用简写:
a.map(&:+ 1)
或:
a.map(&:+ 2)
其中 1 和 2 是参数?
where 1 and 2 are the arguments?
推荐答案
你不能这样做.&
运算符用于将符号转换为过程.
You can't do it like this. The &
operator is for turning symbols into 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`.
&
是 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.
这篇关于如何将参数传递给 array.map 快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文