adbarads adbarads - 2 months ago 8
Ruby Question

ruby how to add a hash element into an existing json array

I have code that outputs the following:

car_id = ["123"]
model = [:model].product(car_id).map { |k,v| {k=>v} }
model = [{:model=>"123"}]


I would like to then add a new hash
:make
into the json like this:

model_with_make = [{:model=>"123", :make => "acura"}]


How do I do this?

Unfortunately, every solution I find produces this:
[{:model=>"123"}, {:make => "acura"}]
and that is not what I want.

Answer
model = [{:model=>"123"}]
model_with_make = model.map { |m| m.merge(make: 'acura') }
#⇒ [{:model=>"123", :make => "acura"}]

If you are concerned that there is the only element in the array model, you might modify it inplace:

model.first.merge!(make: 'acura')
model
#⇒ [{:model=>"123", :make => "acura"}]