Chris
Chris

Reputation: 6246

Inject not working as expected

Can anybody explain why these two snippets of code are not equivalent? Either I am missing something or inject does not do what I think it does. Given:

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

This code:

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

returns

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

But this:

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

returns:

"{:id=>2}"

Why?

Upvotes: 1

Views: 149

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

inject not working as expected

Well, your expectations are wrong. :)

Block to inject/reduce should return the new value of the accumulator.

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

Upvotes: 8

Related Questions