From: Junyoung Kim Date: 2008-11-26T13:53:41+09:00 Subject: Re: How to use a passing argument(returned argument)? Einar's suggestion is very good and clear everything for me :) finally, my code should be changed like --> class Reference def initialize(var_name, vars) @getter = eval "lambda { #{var_name} }", vars @setter = eval "lambda { |v| #{var_name} = v }", vars end def value @getter.call end def value=(new_value) @setter.call(new_value) end end def ref(&block) Reference.new(block.call, block.binding) end def set10(var_a) var_a.value = 10 end a = 22 set10 (ref{:a}) p a thanks for all :) 2008. 11. 26, 오후 1:38, Einar Magnús Boson 작성: > > On 26.11.2008, at 04:19 , Joshua Ballanco wrote: > >> On Nov 25, 2008, at 8:49 PM, 김 준영 wrote: >> >>> Hello, everyone !!! >> >> Hi there! >> >>> I have question about how to use a passing argument. firstly let >>> me show sample code. >>> >>> a = 0 >>> >>> def set10(aArg) >>> aArg = 10 >>> end >>> >>> set10(a) >>> >>> p a <--- I wanna get 10 as a result. >>> >>> >>> How can I do for this one? >> >> First, the pattern you are looking for is not very object oriented- >> y. That is, you're asking to remove some of the logic pertaining to >> 'a' and put it somewhere outside of 'a'. Since 'a' is an object >> (everything in Ruby is), then it would be best if you made 'a' an >> instance of a class with the 'set10' logic in it. The sort of pass- >> by-reference pattern you're looking for is much more typical of C. >> >> That said, this would be, I think, the closest equivalent in Ruby: >> >> a = 0 >> >> def set10(aArg_name, bind) >> eval("#{aArg_name} = 10", bind) >> end >> >> set10('a', binding) >> >> p a >> >> => 10 >> >> Cheers, >> >> Josh >> >> > > > I did not know this, google filled me in and this might be relevant > to the original question: > http://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc/style/print > > They end up with this: > > def swap(aref, bref) > aref.value, bref.value = bref.value, aref.value > end > > a = 22 > b = 33 > swap(ref{:a}, ref{:b}) > p a # => 33 > p b # => 22 > > Pretty neat, if that's something you wanna do. Makes me wonder > though: when I first saw this (5 minutes ago) I thought you might be > able to do > > a = 0 > > def set10(aArg_name, bind=binding) > eval("#{aArg_name} = 10", bind) > end > > set10('a') > > p a > > > but that doesn't work, in what context and when are default-values > evaluated? my guess is that they get the same closure as the method > body and are evaluated on call, is that correct? > > einarmagnus > > > >