adbarads adbarads - 1 year ago 97
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
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 Source
model = [{:model=>"123"}]
model_with_make = { |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=>"123", :make => "acura"}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download