Array#map 如何有参数来做这样的事情? [英] how does Array#map have parameter to do something like this?

查看:27
本文介绍了Array#map 如何有参数来做这样的事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def double(a)
 a*2
end

method_object = method(:double)

这是我的问题,这段代码如何:

and here's my question, how does this code:

[1,3,5,6].map(&method_object)

达到相同的结果

[1,3,5,6].map {|x| method_object.call(x)}

Ruby 文档中,Array#map 只能有块,不能有普通参数

in the Ruby document, the Array#map only can have block, not normal parameter

ary.collect {|item| block } → new_ary ary.map {|item| block } → new_ary ary.collect → an_enumerator ary.map → an_enumerator

推荐答案

简单的说,&符号&是用来将一个方法对象打包/解包"到一个块中的,所以效果是多不一样,就像你通过了块一样.

Simply put, the ampersand & is used to "pack / unpack" a method object to a block, so the effect is more-less the same as if you passed the block.

您可以通过以下方式获取"已传递给您的方法的块:

You can "get" the block that has been passed to your method by:

def method_with_block(&foo)
  # do something here
  foo.call
  # do something else
end

这类似于调用 yield 而不是将 &foo 声明为参数.我认为这两种方法的绑定可能有所不同,但在大多数情况下,效果是您所期望的(如果我弄错了,请更正).

This will be similar to calling yield and not declaring &foo as parameter. I think binding might differ between the two approaches, but in most cases the effect is what you would expect (if I am mistaken, please correct).

当然,&符号的工作方式相反 - 如果一个方法需要一个块并且您有一个 proc 对象,您可以简单地在它前面加上 &,就像您写的那样.更准确地说,& 调用传递对象的 to_proc 方法(Rails 使用这个方法类似于 在关于 to_proc 的条目中描述.

Of course, the ampersand works the other way around - if a method expects a block and you have a proc object, you can simply prepend it with &, just as you wrote. To be more precise, & calls to_proc method of the passed object (Rails uses this in a manner similar to described in this entry about to_proc.

我希望这能解答您的一些疑问.如果我写的有错误,请随时纠正.

I hope that this answers some of your doubts. In case there is a mistake in what I wrote, feel free to correct it.

您可能会觉得有用的阅读:

Readings you might find useful:

  • Programming Ruby, essential book
  • Wikibooks contains a section about this topic
  • This simple blog entry shows an example

这篇关于Array#map 如何有参数来做这样的事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆