Joshua Muheim wrote:
Hi all
PHP lets me easily create multidimensional hashes using the following
syntax:
x = array();
x["bla"]["some_key"] = true;
Is Ruby not capable of doing this?
x =
x[:bla][:some_key] = true
gives me a nil error!
x =
x[:blah][:some_key] = true
--output:--
`': Symbol as array index (TypeError)
from r5test.rb:2
In ruby, array indexes must be non-negative integers-not symbols, not
strings, not floats...err this actually 'works':
x =
x[3.5] = true
puts x[3.5]
--output:--
true
But, I think that ruby must convert the float to an int. However, this
works:
puts x.values_at(3.5)
--output:--
true
But, then so does this:
puts x.values_at(3)
--output:--
true
So, I can't really figure out a way to prove that the index value can't
be a float. Anyway...
To create nested hashes you can do this:
x = {}
x['a'] = 10
p x
x[:bla] = {1=>10, 2=>20}
p x
--output:--
{"a"=>10}
{"a"=>10, :bla=>{1=>10, 2=>20}}
Writing this is problematic, though:
x = {}
x[:bla][:some_key] = true
--output:--
undefined method `=' for nil:NilClass (NoMethodError)
That is equivalent to:
x = {}
lookup1 = x[:bla]
lookup1[:some_key] = true
and when you lookup a non-existent key for a hash, it returns nil. As
a result, lookup1 is assigned nil.
But in ruby you can make hashes to return whatever you want when you
lookup a non-existent key. You do that by specifying what you want
returned in the Hash constructor:
x = Hash.new {|hash, key| hash[key] = {} }
x[:bla][:some_key] = true
p x
--output:--
{:bla=>{:some_key=>true}}
···
--
Posted via http://www.ruby-forum.com/\.