How do I copy a hash in Ruby?

I’ll admit that I’m a bit of a ruby newbie (writing rake scripts, now). In most languages, copy constructors are easy to find. Half an hour of searching didn’t find it in ruby. I want to create a copy of the hash so that I can modify it without affecting the original instance.

Some expected methods that don’t work as intended:

h0 = {  "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
h1=Hash.new(h0)
h2=h1.to_hash

In the meantime, I’ve resorted to this inelegant workaround

def copyhash(inputhash)
  h = Hash.new
  inputhash.each do |pair|
    h.store(pair[0], pair[1])
  end
  return h
end

13 Answers
13

Leave a Comment