Ruby的&方法表示法.到底是怎么回事?

Jwa*_*622 1 ruby

我遇到&method了代码库,我不知道发生了什么.这发生在irb:

[12,3].map(&method(:to_s))
#=> ArgumentError: wrong number of arguments (given 1, expected 0)
["12","3"].map(&method(:Integer))
#=> [12, 3]
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

我熟悉并且等于to_proc,但我仍然无法在这里连接点.

Ser*_*sev 5

In &method(:to_s),.to_s取自当前上下文(顶级对象main).此版本已绑定到接收方,不接受进一步的参数.但是一个参数将通过.map(数组的每个元素)传递,这就是它的作用.

看看这个正在发生的事情的逐步重建

to_s # => "main"
method(:to_s) # => #<Method: main.to_s>
method(:to_s).to_proc # => #<Proc:0x007ff73a27e1e0 (lambda)>
method(:to_s).to_proc.call(12) # => 
# ~> -:6:in `to_s': wrong number of arguments (given 1, expected 0) (ArgumentError)
# ~>    from -:6:in `<main>'
Run Code Online (Sandbox Code Playgroud)

现在比较它会发生什么 .map(&:to_s)

:to_s.to_proc.call(12) # => "12"
Run Code Online (Sandbox Code Playgroud)

我遇到&method了代码库

它在以下情况下非常有用:对每个元素应用一段逻辑,但这个逻辑来自当前上下文,完全在元素外部.看看这个人为的例子:

class Tweet
  attr_accessor :text

  def initialize(text)
    @text = text
  end

  def shortened_links
    find_links.map(&method(:shorten_link))
    # same as
    # find_links.map {|link| shorten_link(link) }
  end

  private

  def find_links
    # detect links in text
  end

  def shorten_link(url)
    # use bit.ly or whatever
  end
end
Run Code Online (Sandbox Code Playgroud)

links是一个字符串集合.他们肯定不能缩短自己.