From: Mohammad Khan Date: 2005-01-19T07:37:42+09:00 Subject: Re: value by reference On Tue, 2005-01-18 at 17:16, Florian Gross wrote: > Mohammad Khan wrote: > > > Before telling my issue, let me show my script: > > > > def do_something(a, b, c) > > a = a + 1 > > b = b + 2 > > c = c + 3 > > end > > a, b, c = 5, 6, 7 > > puts "before do_something:" > > I would like to see the value of a, b, c after calling #do_something as: > > a = 6, b = 8, c = 10 > > > > how can I do it without making a, b, c an instance variable? > > In other words, how can I send value by reference? > > This is not easily done. First of all you should ask yourself why you > find yourself needing it and if there is not a better mechanism in Ruby > that you could use to accomplish your goal. (Methods can return multiple > values.) > I really need it. I could do it by: def do_something(a, b, c) a = a + 1 b = b + 2 c = c + 3 return [a , b, c] end a, b, c = do_something(a, b, c) I don't like to handle with too many return variables but I had to do it in my real project. > After that there's two approaches to addressing the above: > > 1) Supply lambdas: > > def do_something(inc_a, inc_b, inc_c) > inc_a.call(1) > inc_b.call(1) > inc_c.call(1) > end > > do_something( > lambda { |x| a += x }, > lambda { |x| b += x }, > lambda { |x| c += x } > ) What is lambdas? sorry.. if I am asking anything very strange !! I will still prefer to return multiple variables in stead of using these much code! > 2) Use variable.rb to handle variables as Objects: > > def do_something(a, b, c) > a.value += 1 > b.value += 1 > c.value += 1 > end > > do_something(Variable[:a], Variable[:b], Variable[:c]) > > If you find yourself really needing to do this, please follow up with > your reasons. I've not yet found many cases where this is necessary and > would be interested in getting to know about new ones.