【发布时间】:2016-04-24 03:20:03
【问题描述】:
这行得通:
strings = ["1", "2", "3"]
nums = strings.map(&:to_i)
我们看到应用于 Symbol 对象的 & (to_proc 方法) 变成了一个块。 但是,这不起作用:
strings = ["1", "2", "3"]
nums = strings.map(&to_i)
nums = strings.map("to_i".to_sym.to_proc) #...neither does this
为什么它不起作用?没有其他方法可以编写上面的代码吗?我很困惑,因为有两种方法可以访问类的方法:
"1".method(:to_i).call #works as well as
"1".method("to_i").call
所以方法名可以通过符号或字符串访问。
【问题讨论】: