在
ruby中的哈希函数中调用它们时,可以得到如下所示的键和值很好地分离:
{ :a => 1,:b => 2,:c => 3 }.each do |key,value| puts "key is #{key} and value is #{value}" end ========================= key is :a and value is 1 key is :b and value is 2 key is :c and value is 3 => {:a=>1,:b=>2,:c=>3}
但是,使用注入时似乎不起作用.
{ :a => 1,:c => 3 }.inject(0) do |result,key,value| puts "key is #{key} and value is #{value}" result + value end ========================= key is [:a,1] and value is TypeError: nil can't be coerced into Fixnum
在上面的简化示例中,我真的不需要键,所以我可以调用hash.values.inject,但是假设我需要这两个,那么有没有比这个可怕的风格更干净的方式呢?
{ :a => 1,key_and_value| puts "key is #{key_and_value[0]} and value is #{key_and_value[1]}" result + key_and_value[1] end
解决方法
看起来你需要:
{ :a => 1,(key,value)| puts "key is #{key} and value is #{value}" result + value end