I'm trying to create a hash based on an ActiveRecord query in a model
quit_reasons
reasons = quit_reasons.inject({}) do |result, element|
result[element.name] = element.id
end
undefined method `[]=' for 2:Fixnum
Fix is :-
reasons = quit_reasons.inject({}) do |result, element|
result[element.name] = element.id
result
end
The reason is, Hash#[]=
, returns the value is being assigned to the key. As this method Hash#[]=
is your block's last statement, return value of #[]=
is being assigned to the result
, which is causing the error for the next Hash#[]=
call.
I always try to use thus #each_with_object
if I can. Though the object is passed as the first parameter and the result as the second (i.e. the opposite way around to inject)
reasons = quit_reasons.each_with_object({}) do |element, result|
result[element.name] = element.id
end
This one of the most important difference between #inject
and #each_with_object
.