On Thu, 5 Apr 2001, sarayu balu wrote:

> I am brand new to Ruby, and I have been reading Programming Ruby.
> However, I do have a question, having struggled for some time.
> How does the Hash work. I am trying to create a multi-dimensional
> hash. For example,
> h = Hash.new
> h['1']['2'] = '10' gives error undefined methos '[]=' for nil
> h['1'] = '10' is OK
> h['1']['2'] = '10' is OK too
>
Depends on what you want to do. One way would be to do
h[['1','2']] = '10'

otherwise you'll have to create the sub-hashes by hand. I may be wrong but
my impression is that in future Ruby version you might be able to set
default values in a block given at creation time. Like

h = Hash.new {Hash.new}

so that when you do

h[new_val][val] = what_ever

a new hash will be created for new_val.

> print h gives 110nil - this I don't understand
> 
print h.inspect

if you want to have human-readable string.

feldt@CHALMERS1500 /tmp
$ ri Object#inspect
--------------------------------------------------------- Object#inspect
     obj.inspect -> aString
------------------------------------------------------------------------
     Returns a string containing a human-readable representation of obj.
     If not overridden, uses the to_s method to generate the string.
        [ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"
        Time.new.inspect                 #=> "Sun Mar 04 23:29:19 CST
2001"


feldt@CHALMERS1500 /tmp
$ ri Object#to_s
------------------------------------------------------------ Object#to_s
     obj.to_s -> aString
------------------------------------------------------------------------
     Returns a string representing obj. The default to_s prints the
     object's class and an encoding of the object id. As a special case,
     the top-level object that is the initial execution context of Ruby
     programs returns ``main.''


Regards,

Robert