Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

append

ruby

hash

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?

like image 753
Sean Bernardino Avatar asked Feb 08 '15 16:02

Sean Bernardino


1 Answers

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)
like image 131
Rustam A. Gasanov Avatar answered Oct 16 '22 10:10

Rustam A. Gasanov