Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append key/value pair to hash with << in Ruby

Tags:

ruby

hash

In Ruby, one can append values to existing arrays using <<:

a = [] a << "foo" 

but, can you also append key/value pairs to an existing hash?

h = {} h << :key "bar" 

I know you can do:

h[:key] = "" h[:key] << "bar" 

but that's not I want.

Thanks.

like image 694
jcarpio Avatar asked Nov 03 '13 18:11

jcarpio


People also ask

What is << in Ruby?

In ruby '<<' operator is basically used for: Appending a value in the array (at last position) [2, 4, 6] << 8 It will give [2, 4, 6, 8] It also used for some active record operations in ruby.

How do you create a key-value pair in Ruby?

Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas.

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 to add a new key/value pair to a ruby hash?

Ruby hashes since 1.9 maintain insertion order, however. Here are the ways to add new key/value pairs. If you want a method, use store: If you really, really want to use a "shovel" operator ( << ), it is actually appending to the value of the hash as an array, and you must specify the key: The above only works when the key exists.

What is an empty hash in Ruby?

That’s an empty hash! A hash with three key/value pairs looks like this: Where a is a key, and 1 is the corresponding value for that key. Notice that the key-value pairs are separated by commas. Let’s look at how you can use hashes in your Ruby projects with common hash methods.

How do you use a key in a hash?

Using a key, references a value from hash. If the key is not found, returns a default value. Associates the value given by value with the key given by key. Removes all key-value pairs from hash.

What is a hash rocket in Ruby?

By the way, the Ruby community has come up with the name hash rocket for the bit of syntax => which separates a key from a value, … we think that is pretty cool to know :) A Hash is created by listing key/value pairs, separated by hash rockets, and enclosed by curly braces.


1 Answers

There is merge!.

h = {} h.merge!(key: "bar") # => {:key=>"bar"} 
like image 191
sawa Avatar answered Sep 22 '22 22:09

sawa