Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a key/value pair to the beginning of a hash?

Tags:

ruby

hash

My code is:

hash = { two: 2, three: 3 }

def hash_add(hash, new_key, new_value)
  temp_hash = {}

  temp_hash[new_key.to_sym] = new_value
  temp_hash.merge!(hash)
  hash = temp_hash
  puts hash

end

hash_add(hash, 'one', 1)

Within the method, puts hash returns { :one => 1, :two => 2, :three => 3 }, but when hash1 is put to the method, it remains unchanged afterward. It's like the assignment isn't carrying itself outside of the function.

I guess I could return the updated hash and set the hash I want to change to it outside the method:

hash = hash_add(hash, 'one', 1)

But I just don't see why the assignment I give to the hash does not stick outside of the method.

I have this, which works:

def hash_add(hash, new_key, new_value)
  temp_hash = {}

  temp_hash[new_key.to_sym] = new_value
  temp_hash.merge!(hash)
  hash.clear

  temp_hash.each do |key, value|
    hash[key] = value
  end
end

Which gives me what I'm wanting when this method is called, but it just seems a little excessive to have to rebuild the hash like that.

like image 314
Kyle Shike Avatar asked Sep 18 '13 21:09

Kyle Shike


1 Answers

How about this?

hash1 = { two: 2, three: 3 }

#add a new key,value 
hash1 = Hash[:one,1].merge!(hash1) #=> {:one=>1, :two=>2, :three=>3}

Example #2:

h = { two: 2, three: 3 }

def hash_add(h,k,v)
  Hash[k.to_sym,v].merge!(h)
end

h = hash_add(h, 'one', 1) #=> {:one=>1, :two=>2, :three=>3}
like image 168
Bala Avatar answered Oct 04 '22 19:10

Bala