我从Josh Susser举起以下示例
def strip_accents params
thunk = lambda do |key,value|
case value
when String then value.remove_accents!
when Hash then value.each(&thunk)
end
end
params.each(&thunk)
end
当我把它放在 Rails 控制台(irb)中,并用哈希调用它时,我得到以下信息:
ruby-1.9.2-p136 :044 > `ruby --version`
=> "ruby 1.9.2p136 (2010-12-25 revision 30365) [i686-linux]\n"
ruby-1.9.2-p136 :045 > strip_accents({:packs=>{:qty=>1}})
ArgumentError: wrong number of arguments (1 for 2)
from (irb):32:in `block in strip_accents'
from (irb):37:in `each'
from (irb):37:in `strip_accents'
from (irb):45
from /longpathtrimedforclarity/console.rb:44:in `start'
from /longpathtrimedforclarity/console.rb:8:in `start'
from /longpathtrimedforclarity/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
我知道 lambdas 检查 arity,但我在 lambda 定义中看到了两个参数。如果我更改lambda do
为Proc.new do
,代码会执行,我会得到预期的结果。
Josh 的示例来自 2008 年,所以我假设这是 Ruby 1.8 和 1.9 的差异。这里发生了什么?