Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 851
Precipitous Avatar asked Nov 11 '10 17:11

Precipitous


People also ask

How do you copy an object in Ruby?

Ruby does provide two methods for making copies of objects, including one that can be made to do deep copies. The Object#dup method will make a shallow copy of an object. To achieve this, the dup method will call the initialize_copy method of that class. What this does exactly is dependent on the class.

How do you copy a string in Ruby?

We can use the asterisk * operator to duplicate a string for the specified number of times. The asterisk operator returns a new string that contains a number of copies of the original string.

How do you make Hash Hash in Ruby?

Ruby hash creation. A hash can be created in two basic ways: with the new keyword or with the hash literal. The first script creates a hash and adds two key-value pairs into the hash object. A hash object is created.


1 Answers

The clone method is Ruby's standard, built-in way to do a shallow-copy:

irb(main):003:0> h0 = {"John" => "Adams", "Thomas" => "Jefferson"} => {"John"=>"Adams", "Thomas"=>"Jefferson"} irb(main):004:0> h1 = h0.clone => {"John"=>"Adams", "Thomas"=>"Jefferson"} irb(main):005:0> h1["John"] = "Smith" => "Smith" irb(main):006:0> h1 => {"John"=>"Smith", "Thomas"=>"Jefferson"} irb(main):007:0> h0 => {"John"=>"Adams", "Thomas"=>"Jefferson"} 

Note that the behavior may be overridden:

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

like image 101
Mark Rushakoff Avatar answered Sep 26 '22 18:09

Mark Rushakoff