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]
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.)
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.
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.
response = {aa: 'aaa', bb: 'bbb'}
new_response = {new: 'new_value'}.merge(response)
# => {:new=>"new_value", :aa=>"aaa", :bb=>"bbb"}
Try converting it to an array and back:
Hash[hash.to_a.unshift([k, v])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With