0

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.

2 Answers 2

2

Ruby convention for showing result of a calculation

I assume you mean that

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

produces an array containing a single hash:

[{:model=>"123"}]

and that you are not then executing the statement:

model = [{:model=>"123"}]

which would overwrite the the value of model from the previous statement, rendering the previous statement meaningless. If so, the normal way to write that is as follows.

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

Computing the array

Next,

arr = [:model].product(car_id)
  #=> [[:model, "123"]]

But why use Array#product when the arrays [:model] and car_id both contain a single element? It's simpler to just write

arr = [[:model, car_id.first]]
  #=> [[:model, "123"]]

Converting the array to a hash

Since arr contains only one element, there's not much point to mapping it; just convert it to a hash:

Hash[arr]
  #=> {:model=>"123"} 

or (for Ruby versions 1.9+):

arr.to_h
  #=> {:model=>"123"} 

Add a key-value pair to the hash

If you wish to add the key-value pair :make => "acura" to

h = {:model=>"123"} 

you can simply write

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

or, in one line,

(h[:make] = "acura") && h
  #=> {:model=>"123", :make=>"acura"}

Wrapping up

Putting this together, you could write

h = [[:model, car_id.first]].to_h
  #=> {:model=>"123"} 
(h[:make] = "acura") && h
  #=> {:model=>"123", :make=>"acura"} 
Sign up to request clarification or add additional context in comments.

Comments

1
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"}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.