我们知道,我们可以通过 &:
前缀将方法传递给迭代器方法。
例如:
["a", "b"].map(&:upcase) #=> ["A", "B"]
def rettwo
2
end
["a", "b"].map(&:rettwo) #=> [2, 2]
问题来了,当我写一个方法,传递一个带有 &:
前缀的方法时,我得到一个错误信息:“ArgumentError: no receiver given”。
让我展示代码:
def a_simple_method &proc
puts proc.class # it shows `Proc`
proc.call
end
def a_iterator_method
puts yield
end
a_simple_method &:rettwo #=> ArgumentError: no receiver given
a_iterator_method &:rettwo #=> ArgumentError: no receiver given
我遗漏了什么,map
之类的 Array 方法如何处理它
最佳答案
这是有效的。解释如下。
class String
def rettwo
self + self
end
end
def a_simple_method &proc
proc.call('a')
end
def a_iterator_method
yield 'b'
end
a_simple_method(&:rettwo) # => "aa"
a_iterator_method(&:rettwo) # => "bb"
&:
构造称为 Symbol#to_proc
。它将符号变成一个过程。这个过程需要一个接收者作为第一个参数。其余参数用于调用 proc。您没有传递任何参数,因此出现“未给出接收者”错误。
这是附加参数的演示:
class String
def say name
"#{self} #{name}"
end
end
def a_simple_method &proc
proc.call('hello', 'ruby')
end
a_simple_method(&:say) # => "hello ruby"
这是2008年的一些博文中对Symbol#to_proc的定义。现代Symbol#to_proc似乎是用C实现的,但这仍然有助于理解。
class Symbol
def to_proc
Proc.new { |*args| args.shift.__send__(self, *args) }
end
end
关于ruby - 将方法传递给迭代器方法时发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13365452/