简体   繁体   English

调用所有数组元素的函数,而不将item作为参数传递

[英]Call function for all array elements without passing item as parameter

In javascript I can do this: 在javascript中,我可以这样做:

var show = function(w) {
  alert(w);
};

var words =  ['a', 'b', 'c'];
words.forEach(show);

Note that I don't need to pass the array item as a parameter. 请注意,我不需要将数组项作为参数传递。

Is there a way to the same in ruby? 有没有办法在红宝石中做到相同?

Like: 喜欢:

def show(w)
  puts w
end

words = ['a', 'b', 'c']
words.each(show)

PS: I know that I can do it by doing: words.each { |w| show(w) } PS:我知道我可以这样做: words.each { |w| show(w) } words.each { |w| show(w) } . words.each { |w| show(w) } The question is if I can do it like in javascript, without passing the item as a parameter. 问题是我是否可以像在javascript中那样进行操作,而无需将该项目作为参数传递。

Sure, you do it by passing the method, just like you do in ECMAScript: 当然,您可以通过传递方法来完成此操作,就像在ECMAScript中一样:

words.each(&method(:show))

Note that this is the way to make your Ruby example work. 请注意,这是使Ruby示例正常工作的方法。 However, a Ruby method is not really the closest analogue to an ECMAScript function in Ruby. 但是,Ruby方法实际上并不是最接近Ruby中ECMAScript函数的类似方法。 A Proc would actually be a closer match: 实际上, Proc会更接近:

show = -> w { puts w }

words.each(&show)

This actually reads very close to the ECMAScript 6 version: 实际上,这与ECMAScript 6版本非常接近:

const show = w => alert(w);

words.forEach(show);

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

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