I would be happy to access any element of multi-dimensional hash-array by a shorter expression
h = {a: {b: 'c'}}
# default way
p h[:a][:b] # => "c"
# a nicer way
p h[:a,:b] # => "c"
# nice assignment
h[:a,:b] = 1
p h # => {:a=>{:b=>1}}
I realize that in this way one eliminates the possibility to have a hash key being an array.
{[:a,:b] => "c"}
Since it is quite rare situation, I would prefer to reduce number of [] in my expressions.
How can one achieve this?
Update
Ok, I wasn't clear. The problem is that I have tried to make custom []
and []=
methods myself, but failed. Could you show me how such functionality can be implemented?
Multi-dimensional arrays
If you are looking for something similar for arrays, have a look on narray
gem http://narray.rubyforge.org/
>> a = NArray.int(5,5)
=> NArrayint5,5:
[ [ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ] ]
>> a[1,2]
=> 0
>> a[1,2]=1
=> 1
>> a
=> NArrayint5,5:
[ [ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 1, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ] ]
>> a[1,0..4]=1
=> 1
>> a
=> NArrayint5,5:
[ [ 0, 1, 0, 0, 0 ],
[ 0, 1, 0, 0, 0 ],
[ 0, 1, 0, 0, 0 ],
[ 0, 1, 0, 0, 0 ],
[ 0, 1, 0, 0, 0 ] ]