How to extend Hash

I am trying to extend the Hash class so that I can “Insert the content
of a Hash object to another Hash object”.

However, the internal code for Hash is written in c. Is it possible to
extend the class using ruby itself? How, since we don’t know the
internal data structures of class Hash.

Can some expert enlighten me?

Hi,

···

In message “How to extend Hash” on 03/01/02, TOTO zhoujing@comp.nus.edu.sg writes:

I am trying to extend the Hash class so that I can “Insert the content
of a Hash object to another Hash object”.

However, the internal code for Hash is written in c. Is it possible to
extend the class using ruby itself? How, since we don’t know the
internal data structures of class Hash.

It is possible, just like other Ruby-defined classes. But first you
can check out “update” method for Hash class.

						matz.

------------------------------------------------------------ Hash#update
hsh.update( anOtherHash ) → hsh

 Adds the contents of anOtherHash to hsh, overwriting entries with
 duplicate keys with those from anOtherHash.
    h1 = { "a" => 100, "b" => 200 }
    h2 = { "b" => 254, "c" => 300 }
    h1.update(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}

matz@ruby-lang.org (Yukihiro Matsumoto) wrote in message news:1041481402.405681.3205.nullmailer@picachu.netlab.jp

Hi,

I am trying to extend the Hash class so that I can “Insert the content
of a Hash object to another Hash object”.

However, the internal code for Hash is written in c. Is it possible to
extend the class using ruby itself? How, since we don’t know the
internal data structures of class Hash.

It is possible, just like other Ruby-defined classes. But first you
can check out “update” method for Hash class.

  					matz.

------------------------------------------------------------ Hash#update
hsh.update( anOtherHash ) → hsh

 Adds the contents of anOtherHash to hsh, overwriting entries with
 duplicate keys with those from anOtherHash.
    h1 = { "a" => 100, "b" => 200 }
    h2 = { "b" => 254, "c" => 300 }
    h1.update(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}

Thanks. Yes. That is exactly what I wanted.

However, I still don’t understand how I can add methods to class Hash
with Ruby, since I don’t know the internal structure of it.

Thank you very much!

···

In message “How to extend Hash” > on 03/01/02, TOTO zhoujing@comp.nus.edu.sg writes:

However, I still don't understand how I can add methods to class Hash
with Ruby, since I don't know the internal structure of it.

pigeon% cat b.rb
#!/usr/bin/ruby
class Hash
   def insert(a, b)
      self[a] = b
   end
end

h = {1 => 2}
h.insert(2, 3)
p h
pigeon%

pigeon% b.rb
{1=>2, 2=>3}
pigeon%

Guy Decoux