Quick way to copy data from super class into subclass?

Discussion in 'Ruby' started by Audrey A Lee, Feb 22, 2010.

  1. Audrey A Lee

    Audrey A Lee Guest

    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
    Audrey A Lee, Feb 22, 2010
    #1
    1. Advertising

  2. 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
    Joel VanderWerf, Feb 22, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Guest

    super.super.super how?

    Guest, Feb 19, 2005, in forum: Java
    Replies:
    24
    Views:
    10,739
    Darryl Pierce
    Feb 24, 2005
  2. Fernando Rodriguez

    Getting the super class via the super() function

    Fernando Rodriguez, Nov 21, 2003, in forum: Python
    Replies:
    2
    Views:
    708
    Bob Willan
    Nov 22, 2003
  3. yousay
    Replies:
    2
    Views:
    773
    Jean-Michel Pichavant
    Jan 21, 2010
  4. fi3nd
    Replies:
    0
    Views:
    371
    fi3nd
    Apr 8, 2010
  5. Trans
    Replies:
    8
    Views:
    305
    Robert Klemme
    Oct 23, 2008
Loading...

Share This Page