From: "Iñaki Baz Castillo" Date: 2008-04-25T01:24:36+09:00 Subject: Re: Pointer concept in Ruby ? 2008/4/24, Mikael Høilund : > > On Apr 24, 2008, at 18:01, Iñaki Baz Castillo wrote: > > > > Hi, I'd like to have a variable pointing to a Hash/Array element, so > > if I modify the variable then the Hash/Array element is modified too. > > > > AFAIK this is not possible with Ruby since the abscense of pointer > > concept. I want the following: > > > > array = [ "aaa", "bbb", "ccc" ] > > > > a1 = array[1]._some_method_ > > => "bbb" > > > > a1 = "BBB" > > => "BBB" > > > > a[1] > > => "BBB" > > > > Is it possible in some way? Thanks a lot. > > > > > > -- Iñaki Baz Castillo > > > > > > Quoth irb: > > >> array = [ "aaa", "bbb", "ccc" ] > => ["aaa", "bbb", "ccc"] > >> a1 = array[1] > => "bbb" > >> a1.upcase! > => "BBB" > >> array > => ["aaa", "BBB", "ccc"] > >> > > You never pass by value, so you're in essence always dealing with pointers. > With your example, you merely made a1 point at a different object, a new > string, instead of the second string in the array. Yes, I know that since object_id is the same **until** a write operation is done. > If you however call a self-modifying method on a1 while it's pointing at > the array string, it'll also change in the array, as it's still pointing at > the same object. No, that's not true. Demostration: array=[000,111,222,33] => [0, 111, 222, 33] a1=a[1] => 1 a[1].object_id => 345 a1.object_id => 345 a1="NEW VALUE" => "NEW VALUE" > a1.object_id => -606081098 <----------- Has changed !!! a[1].object_id <-------- Remains the same => 345 a1 => "NEW VALUE" a[1] => 1 <----------- Original value not changed > What are you trying to achieve in practice? In fact just the code I wrote as example :) -- Iñaki Baz Castillo