109

In regards to adding an key => value pair to an existing populated hash in Ruby, I'm in the process of working through Apress' Beginning Ruby and have just finished the hashes chapter.

I am trying to find the simplest way to achieve the same results with hashes as this does with arrays:

x = [1, 2, 3, 4]
x << 5
p x

7 Answers 7

211

If you have a hash, you can add items to it by referencing them by key:

hash = { }
hash[:a] = 'a'
hash[:a]
# => 'a'

Here, like [ ] creates an empty array, { } will create a empty hash.

Arrays have zero or more elements in a specific order, where elements may be duplicated. Hashes have zero or more elements organized by key, where keys may not be duplicated but the values stored in those positions can be.

Hashes in Ruby are very flexible and can have keys of nearly any type you can throw at it. This makes it different from the dictionary structures you find in other languages.

It's important to keep in mind that the specific nature of a key of a hash often matters:

hash = { :a => 'a' }

# Fetch with Symbol :a finds the right value
hash[:a]
# => 'a'

# Fetch with the String 'a' finds nothing
hash['a']
# => nil

# Assignment with the key :b adds a new entry
hash[:b] = 'Bee'

# This is then available immediately
hash[:b]
# => "Bee"

# The hash now contains both keys
hash
# => { :a => 'a', :b => 'Bee' }

Ruby on Rails confuses this somewhat by providing HashWithIndifferentAccess where it will convert freely between Symbol and String methods of addressing.

You can also index on nearly anything, including classes, numbers, or other Hashes.

hash = { Object => true, Hash => false }

hash[Object]
# => true

hash[Hash]
# => false

hash[Array]
# => nil

Hashes can be converted to Arrays and vice-versa:

# Like many things, Hash supports .to_a
{ :a => 'a' }.to_a
# => [[:a, "a"]]

# Hash also has a handy Hash[] method to create new hashes from arrays
Hash[[[:a, "a"]]]
# => {:a=>"a"} 

When it comes to "inserting" things into a Hash you may do it one at a time, or use the merge method to combine hashes:

{ :a => 'a' }.merge(:b => 'b')
# {:a=>'a',:b=>'b'}

Note that this does not alter the original hash, but instead returns a new one. If you want to combine one hash into another, you can use the merge! method:

hash = { :a => 'a' }

# Returns the result of hash combined with a new hash, but does not alter
# the original hash.
hash.merge(:b => 'b')
# => {:a=>'a',:b=>'b'}

# Nothing has been altered in the original
hash
# => {:a=>'a'}

# Combine the two hashes and store the result in the original
hash.merge!(:b => 'b')
# => {:a=>'a',:b=>'b'}

# Hash has now been altered
hash
# => {:a=>'a',:b=>'b'}

Like many methods on String and Array, the ! indicates that it is an in-place operation.

3
  • 15
    A lot of valuable information, but lacking the most basic formulation as answered so simply by @robbrit.
    – danh
    Commented Aug 22, 2013 at 15:27
  • 1
    Please edit your answer to actually answer the question that was asked, somewhere near the top preferably. It would be rude of me to do it for you.
    – Stephan
    Commented Sep 29, 2014 at 7:07
  • @Stephan Added a more concise example at the top.
    – tadman
    Commented Sep 30, 2014 at 15:08
66
my_hash = {:a => 5}
my_hash[:key] = "value"
1
  • It doesn't work now: line_item[:brain] = "HELLO" Raises error: can't write unknown attribute brain Commented Apr 29, 2022 at 13:42
39

If you want to add more than one:

hash = {:a => 1, :b => 2}
hash.merge! :c => 3, :d => 4
p hash
9
x = {:ca => "Canada", :us => "United States"}
x[:de] = "Germany"
p x
4
  • I've tried to implement this with the following: x['key'] = "value" however I am receiving errors. I should mention I am working with strings.
    – Tom
    Commented Jul 28, 2011 at 18:49
  • 1
    What's the error? It could be anything unless you are more specific.
    – tadman
    Commented Jul 28, 2011 at 19:03
  • It doesn't work: line_item[:brain] = "HELLO" Raises error: can't write unknown attribute brain Commented Apr 29, 2022 at 13:43
  • @AnasAnsari it seems like line_item isn't a Hash in your code Commented May 3, 2022 at 19:51
2

You can use double splat operator which is available since Ruby 2.0:

h = { a: 1, b: 2 }
h = { **h, c: 3 }
p h
# => {:a=>1, :b=>2, :c=>3}
1
hash = { a: 'a', b: 'b' }
 => {:a=>"a", :b=>"b"}
hash.merge({ c: 'c', d: 'd' })
 => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 

Returns the merged value.

hash
 => {:a=>"a", :b=>"b"} 

But doesn't modify the caller object

hash = hash.merge({ c: 'c', d: 'd' })
 => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 
hash
 => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 

Reassignment does the trick.

1
  • IT doesn't work: line_item.merge({line_total: "YYEYAH"}). Raises: undefined method `merge' Line_item. Commented Apr 29, 2022 at 13:46
0
hash {}
hash[:a] = 'a'
hash[:b] = 'b'
hash = {:a => 'a' , :b = > b}

You might get your key and value from user input, so you can use Ruby .to_sym can convert a string to a symbol, and .to_i will convert a string to an integer.
For example:

movies ={}
movie = gets.chomp
rating = gets.chomp
movies[movie.to_sym] = rating.to_int
# movie will convert to a symbol as a key in our hash, and 
# rating will be an integer as a value.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.