2013-02-20 42 views
1

任何人都可以解釋爲什麼這兩個代碼片段不等效?要麼我錯過了一些東西,要麼注射不會做我認爲的事情。鑑於:注入不按預期工作

nodes = [{id: 1}, {id: 2}] 

此代碼:

result = Hash.new 
nodes.each do |node| 
    result[node[:id]] = node.inspect 
end 
result 

回報

{ 
    1 => "{:id=>1}", 
    2 => "{:id=>2}" 
} 

但這:

nodes.inject({}) {|hash, node|hash[node[:id]] = node.inspect} 

回報:

"{:id=>2}" 

爲什麼?

回答

8

注入工作不正常

那麼,你的期望是錯誤的。 :)

塊到inject/reduce應返回累加器的新值。

nodes = [{id: 1}, {id: 2}] 
res = nodes.inject({}) {|hash, node| hash[node[:id]] = node.inspect; hash} 
res # => {1=>"{:id=>1}", 2=>"{:id=>2}"} 
+0

謝謝!天色已晚,知道我正在變厚! – Chris 2013-02-20 17:14:05