I have a loop building a hash for use in a select field. The intention is to end up with a hash:
{ object.id => "object name", object.id => "object name" }
Using:
@hash = {}
loop_over.each do |ac|
@hash[ac.name] = ac.id
end
I think that the map
method is meant for this type of situation but just need some help understanding it and how it works. Is map
the right method to refactor this each
loop?
Data transformations like this are better suited to each_with_object
:
@hash = loop_over.each_with_object({}) { |ac, h| h[ac.name] = ac.id }
If your brain is telling you to use map
but you don't want an array as the result, then you usually want to use each_with_object
. If you want to feed the block's return value back into itself, then you want inject
but in cases like this, inject
requires a funny looking and artificial ;h
in the block:
@hash = loop_over.inject({}) { |h, ac| h[ac.name] = ac.id; h }
# -------------------- yuck -----------------------------^^^
The presence of the artificial return value is the signal that you want to use each_with_object
instead.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments