Eric Mahurin wrote:
In ruby, is there a way to get a handle of an object reference?
In perl, this is the \ operator:
$x = 1; # \$x is a handle to change $x
$a = [1,2,3]; # \$a->[1] is a handle to change an element in $a
As far as I can tell, the closest that Ruby has to this is a
symbol. But, this only works for object references that have
an associated variable name. For example, there is no symbol
associated with an element of an array (or hash).
You can do something like this with closures:
irb(main):001:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> set_a_1, get_a_1 = proc {|v| a[1]=v}, proc {a[1]}
=> [#<Proc:0x401e8a6c@(irb):2>, #<Proc:0x401e89b8@(irb):2>]
irb(main):003:0> set_a_1[5]
=> 5
irb(main):004:0> a
=> [1, 5, 3]
irb(main):005:0> get_a_1
=> 5
Note that if the binding of a changes, then set_a_1 and get_a_1 refer to the new value. If you want the two procs always to refer to the same array, you need to introduce a new variable (probably better be in a new scope, as well):
irb(main):009:0> def make_elt_1_refs(x)
irb(main):010:1> [proc {|v| x[1]=v}, proc {x[1]}]
irb(main):011:1> end
=> nil
irb(main):012:0> set_1, get_1 = make_elt_1_refs(a)
=> [#<Proc:0x401f6f18@(irb):10>, #<Proc:0x401f6e00@(irb):10>]
irb(main):013:0> a =
=>
irb(main):014:0> get_1
=> 5