Hi --

On Thu, 23 Jul 2009, Pavel Smerk wrote:

> David A. Black wrote:
>> 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"}}}
>
> Yes, but I need something like:
>
> $ ruby -e 'h = { :a => { :b => "hi" } }; tmp = h[:a][:b]; tmp << " there"; p 
> h'
> {:a=>{:b=>"hi there"}}
>
> which is OK, but not for Float:
>
> $ ruby -e 'h = { :a => { :b => 5.0 } }; tmp = h[:a][:b]; tmp += 5.0; p h'
> {:a=>{:b=>5.0}}
>
> And that's why I'm asking for a "real" reference, because tmp apparently is 
> not any kind of reference to the h[:a][:b].

Right; I wasn't taking into account the fact that your example was
dealing with numbers.

>> 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.
>
> Mhm, an unfortunate difference, I'm afraid...

You'll have to talk to Larry about fixing it :-) Seriously though... I
would advise you strongly not to compare Ruby and Perl token-by-token
or construct-by-construct. It's like criticizing a flute because it
doesn't have strings.


> Of course, I could write tmp = h[:a] and then many times tmp[:b]. But 
> something like simple tmp as in Perl would seem to me far more elegant.

The two languages have completely different variable and assignment
semantics. Again, I'd try to get to know Ruby on its own terms.
There's plenty of elegance to be had there :-)


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)