From: David Masover Date: 2008-09-16T12:48:48+09:00 Subject: Re: pass by reference in each loop On Monday 15 September 2008 16:16:11 Xiong Chiamiov wrote: > But not what I was trying to do, which is to change the array, and have > the values propagate backwards: > > irb(main):001:0> a = 1 > => 1 > irb(main):002:0> b = 2 > => 2 > irb(main):003:0> c = 3 > => 3 > irb(main):004:0> arr = [a, b, c] > => [1, 2, 3] > irb(main):005:0> arr[0] = 0 > => 0 > irb(main):006:0> a > => 1 I'm not sure if you were asking for help, but I wanted to show off. Ruby doesn't work the way you describe, but it can fake it pretty well. You're going to have to use something other than variables, like methods: arr = [1,2,3] def a arr[0] end def b arr[1] end def c arr[2] end That's a lot of repetition, though, so I'd do this instead: arr = [1,2,3] %w{a b c}.each_with_index do |name, index| define_method name do arr[index] end end Or, if you're only going to be manipulating it once, you could just unpack the array into variables when you're done: arr = [1,2,3] arr[0] = 0 a,b,c = arr Or you could bypass the whole issue and use a hash instead of an array, if that fits what you're looking for. One more solution: Make something that looks like an array, but isn't: class FakeArray VARS = [:a, :b, :c] attr_accessor *VARS def [] index self.send VARS[index] end def []= index, value self.send "#{VARS[index]}=", value end def what_you_wanted a = 1 b = 2 c = 3 self[0] = 0 puts "a is #{a}" end # And if you want it to be even more array-like: include Enumerable def each VARS.each do |var| yield(self.send var) end end def length VARS.length end end I'll leave it as an exercise to the reader to figure out how to separate the pseudo-array from the class where a, b, and c are defined. This provides a bit more flexibility, as you could then have more than one pseudo-array: arr1 = self.pseudo_array(:a, :b, :c) arr2 = self.pseudo_array(:c, :b, :a) arr1[0] = 42 # or whatever # This should be true, then: arr1[0] == arr2[2] == self.a There is one possibility I haven't covered, which is how to actually wrap a variable in a reference. I haven't covered that mostly because it isn't really helpful here -- no matter how magical I make my IntegerWrapper, it will be completely discarded when you do: arr[0] = 0 Because that "arr[0] =" is calling a method on the array itself, not doing anything to the object stored inside it.