Mikael Høilund
4/24/2008 4:08:00 PM
On Apr 24, 2008, at 18:01, I=F1aki 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 =3D [ "aaa", "bbb", "ccc" ]
>
> a1 =3D array[1]._some_method_
> =3D> "bbb"
>
> a1 =3D "BBB"
> =3D> "BBB"
>
> a[1]
> =3D> "BBB"
>
> Is it possible in some way? Thanks a lot.
>
>
> -- =20
> I=F1aki Baz Castillo
> <ibc@aliax.net>
Quoth irb:
>> array =3D [ "aaa", "bbb", "ccc" ]
=3D> ["aaa", "bbb", "ccc"]
>> a1 =3D array[1]
=3D> "bbb"
>> a1.upcase!
=3D> "BBB"
>> array
=3D> ["aaa", "BBB", "ccc"]
>>
You never pass by value, so you're in essence always dealing with =20
pointers.
With your example, you merely made a1 point at a different object, a =20
new string, instead of the second string in the array.
If you however call a self-modifying method on a1 while it's pointing =20=
at the array string, it'll also change in the array, as it's still =20
pointing at the same object.
What are you trying to achieve in practice?=