Christian
Christian

Reputation: 5521

Which is the best way to update a hash within a hash?

Is there is a better way to update a value in a hash within a hash?

For example:

result_hash = {
   id: queue[:id],
   status:
   {
     added: 0, 
     updated: 0,
     rejected: 0
   }
}

I used one of the two lines below:

result_hash[:status][:updated] += 1
result_hash[:status][:added] += 1

but read about hash.update. When I tried it, only the first value ":added" was updated.

Are there any alternatives or can anyone explain how to use hash.update in my case?

Upvotes: 2

Views: 121

Answers (1)

Cristian Lupascu
Cristian Lupascu

Reputation: 40526

Here's a way in which you could use update to achieve the same task:

result_hash[:status].update({
  added: result_hash[:status][:added] + 1,
  updated: result_hash[:status][:updated] + 1,
})

However, I think update is not beneficial in this case, and I find your existing code much cleaner and more readable.

Upvotes: 2

Related Questions