Hi --

On Thu, 23 Jul 2009, Pavel Smerk wrote:

> Assume a big hash and/or a nested structure and the need of a plenty of 
> operations on some hash[...][...][...] which is Float. How can one avoid the 
> repetitious evaluation of the indices? I have not been able to get a "real" 
> reference to that variable to do _something_like_ tmp = 
> referenceof(hash[...][...][...]) and work with the value directly through the 
> (dereferenced) tmp variable. In Perl I would say
>
> $ perl -e '$x[1][2][3] = 1; $a = \$x[1][2][3]; $$a = 3; print $x[1][2][3]'
> 3
>
> (where \... is a reference and $ before $a is a dereference).

h = { :a => { :b => {} } }
tmp = h[:a][:b]
tmp[:x] = "hi"
tmp[:x] << " there"
p h                 # => {:a=>{:b=>{:x=>"hi there"}}}

You're (almost) always dealing in references in Ruby. (And the almost
part doesn't affect you much anyway.) Every reference is exactly one
step away from the object; there's no such thing as a reference to a
reference. It's very different from Perl in that respect.

> Morover, why the return value of the assignment is not an l-value? The 
> following is legal in Perl ($x ||= 1) *= 2 --- why it is not legal in Ruby as 
> well?

I assume it's because (x ||= 1) evaluates to the object 1, and 1 *= 2
doesn't make sense.


David

-- 
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (http://manning.com/black2)
Training! Intro to Ruby, with Black & Kastner, September 14-17
(More info: http://rubyurl.com/vmzN)