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)
Inside the method puts hash returns { :one => 1, :two => 2, :three => 3 } hash1 { :one => 1, :two => 2, :three => 3 } hash1 { :one => 1, :two => 2, :three => 3 } , but when hash1 is placed in the method, it remains unchanged after that. It looks like an assignment does not carry itself out of function.
I assume that I can return the updated hash and set the hash that I want to change outside the method:
hash = hash_add(hash, 'one', 1)
But I just donβt understand why the assignment that I pass the hash does not stick outside the method.
I have this that 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 want when this method is called, but it just seems like it is too difficult to rebuild such a hash.
ruby hash
qrrr
source share