Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert element at the beginning of Ruby Hash?

Tags:

ruby

hash

I have a use-case where I have an existing hash:

response = { aa: 'aaa', bb: 'bbb' }

I need to add id as one of the keys.

When I use response.merge(id: 'some_id') and then convert it into JSON, I got id as the last element, which I don't want.

I want to insert id: 'some_id' at the beginning of response. I have tried this, but it doesn't feel good to iterate over it:

new_response = { id: 'some id' }
response.keys.reverse.each {|key| new_response[key] = response[key] }

Basically, I need a similar feature like Ruby Array's unshift.

irb(main):042:0> arr = [1, 2, 3]
=> [1, 2, 3]
irb(main):043:0> arr.unshift(5)
=> [5, 1, 2, 3]
like image 331
brg Avatar asked Dec 24 '13 10:12

brg


People also ask

How do you add hash to hash?

Merge two hashes On of the ways is merging the two hashes. In the new hash we will have all the key-value pairs of both of the original hashes. If the same key appears in both hashes, then the latter will overwrite the former, meaning that the value of the former will disappear. (See the key "Foo" in our example.)

How do I iterate a hash in Ruby?

Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.

How do you add a hash to an array in Ruby?

In Ruby, a new key-value pair can be added to a hash using bracket notation. The new key is bracketed after the name of the hash and then the value is assigned after the equals sign.


2 Answers

response = {aa: 'aaa', bb: 'bbb'}
new_response = {new: 'new_value'}.merge(response)
# => {:new=>"new_value", :aa=>"aaa", :bb=>"bbb"}
like image 165
sawa Avatar answered Oct 04 '22 12:10

sawa


Try converting it to an array and back:

Hash[hash.to_a.unshift([k, v])]
like image 45
Denis de Bernardy Avatar answered Oct 04 '22 13:10

Denis de Bernardy