为什么有些方法可以使用注入而有些方法不适用?

Bal*_*ala 1 ruby

我明白我可以传递一个方法inject.例如,

[1,2,3].inject(:+)     #=> 6
Run Code Online (Sandbox Code Playgroud)

但这一个抛出

["1","2","3"].inject(:to_i) #=> TypeError: no implicit conversion of String into Integer
["1","2","3"].inject(:to_s) #=> ArgumentError: wrong number of arguments (1 for 0)
Run Code Online (Sandbox Code Playgroud)

我没有做任何特别的事情,只是想让我的基础知识正确.

Chu*_*uck 5

简短的解释是" inject必须采取两个论点的回调".但这可能不会完全清除它.

好的,让我们看一下普通的注入块形式:

[1, 2, 3].inject {|memo, number| memo + number}
Run Code Online (Sandbox Code Playgroud)

传递符号的方式相同 - 它只是将符号转换为代替块的proc.将符号转换为proc时,转换如下所示:

class Symbol
  def to_proc
    proc {|receiver, *args| receiver.send(self, *args) }
  end
end
Run Code Online (Sandbox Code Playgroud)

所以当你传递时:+,它会调用+memo值的方法,当前的数字作为参数,就像1 + 2.

所以当你通过时:to_i,它等同于:

["1", "2", "3"].inject {|memo, number_string| memo.to_i(number_string) }
Run Code Online (Sandbox Code Playgroud)

但这没有任何意义.您正在尝试将字符串作为参数传递给to_i.这是无效的.

  • 好答案.某人可能感兴趣的一个小细节:在Chuck的倒数第二行,因为`inject`没有给出参数,`memo`最初被赋予数组的第一个元素(`"1"`),所以异常发生当Ruby遇到"1".to_i("2")`时. (2认同)