Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Ruby (http://www.velocityreviews.com/forums/f66-ruby.html)
-   -   Quick way to copy data from super class into subclass? (http://www.velocityreviews.com/forums/t861816-quick-way-to-copy-data-from-super-class-into-subclass.html)

Audrey A Lee 02-22-2010 07:36 PM

Quick way to copy data from super class into subclass?
 
Hello Ruby people,

I want to create a subclass of Hash.

I want to call it MyHash.

I know how to do that.

Next I want to create objects from MyHash like:
@my_hash= MyHash.new

So, I know how to do that.

I need help with transferring data from an ordinary hash-object into
@my_hash

Suppose I have this:
@your_hash= {:k1 => 1, :k2 => 2}

Is there a quick way or idiom to copy the data from @your_hash into
@my_hash?

I tried this:

ruby-1.8.7-p174 > @your_hash= {:k1 => 1, :k2 => 2}
=> {:k2=>2, :k1=>1}

ruby-1.8.7-p174 > class MyHash < Hash ; end
=> nil

ruby-1.8.7-p174 > @my_hash= MyHash.new @your_hash
=> {}

ruby-1.8.7-p174 > @my_hash
=> {}

--Audrey

Joel VanderWerf 02-22-2010 07:49 PM

Re: Quick way to copy data from super class into subclass?
 
Audrey A Lee wrote:
> Is there a quick way or idiom to copy the data from @your_hash into
> @my_hash?


Use Hash#update:

>> class MyHash < Hash; end

=> nil
>> h = {1=>2}

=> {1=>2}
>> mh = MyHash.new

=> {}
>> mh.update h

=> {1=>2}
>> mh.class

=> MyHash




All times are GMT. The time now is 11:27 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.