How do I append a key value pair to an existing hash in Ruby?

15,187

Solution 1

There are 3 ways:

.merge(other_hash) Returns a new hash containing the contents of other_hash and the contents of hsh.

hash = { a: 1 }
puts hash.merge({ b: 2, c: 3 }) # => {:a=>1, :b=>2, :c=>3}

.merge!(other_hash) Adds the contents of other_hash to hsh.

hash = { a: 1 }
puts hash.merge!({ b: 2, c: 3 }) # => {:a=>1, :b=>2, :c=>3}

And most efficient way is to modify existing hash, setting new values directly:

hash = { a: 1 }
hash[:b] = 2
hash[:c] = 3
puts hash # => {:a=>1, :b=>2, :c=>3}

Corresponding Benchmarks for these methods:

       user     system      total        real
   0.010000   0.000000   0.010000 (  0.013348)
   0.010000   0.000000   0.010000 (  0.003285)
   0.000000   0.000000   0.000000 (  0.000918)

Solution 2

You can merge! the two hashes together:

hash1 = {}
hash1.merge!({"a" => 1, "b" => 2})
Share:
15,187
Sean Bernardino
Author by

Sean Bernardino

Updated on June 08, 2022

Comments

  • Sean Bernardino
    Sean Bernardino about 2 years

    I'm new to Ruby and am trying to 'inject' key/value pairs to an existing hash in Ruby. I know you can do this with << for arrays, for e.g.

    arr1 = []
    a << "hello"
    

    But could I do something similar for a hash? So something like

    hash1 = {}
    hash1 << {"a" => 1, "b" => 2}
    

    Basically, I'm trying push key value pairs in a loop based on a condition.

    # Encoder: This shifts each letter forward by 4 letters and stores it  in a hash called cipher. On reaching the end, it loops back to the first letter
    def encoder (shift_by)
    alphabet = []
    cipher = {}
    alphabet =  ("a".."z").to_a
    alphabet.each_index do |x|
            if (x+shift_by) <= 25
                cipher = {alphabet[x] => alphabet[x+shift_by]}
            else
                cipher = {alphabet[x] => alphabet[x-(26-shift_by)]} #Need this piece to push additional key value pairs to the already existing cipher hash.
            end
    end
    

    Sorry for pasting my whole method here. Can anyone please help me with this?

  • Sean Bernardino
    Sean Bernardino over 9 years
    Thank you. This worked well.