From: Michael Strelnikov Date: 2007-03-12T18:31:02+09:00 Subject: Re: #define alternative for Ruby ------=_Part_12964_3070219.1173691859222 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 3/12/07, Brian Candler wrote: > > On Mon, Mar 12, 2007 at 06:05:25PM +0900, Mike wrote: > > > > Imagine you would call the function with rand() as parameter. With > #define > > > > value would be used three times. > > > > > > ??? > > > > > > irb(main):001:0> def myfunc(x); Math.sin(x)*Math.cos(x)*Math.exp(x); > end > > > => nil > > > irb(main):002:0> p myfunc(rand) > > > 0.44720293351854 > > > => nil > > > irb(main):003:0> p myfunc(rand) > > > 1.07121692170638 > > > => nil > > > irb(main):004:0> p myfunc(rand) > > > 1.01827292445777 > > > => nil > > > > > > Now, if you *store* the value of rand within the function, that's a > > > different case. But Ruby has different idioms for deferred execution: > one of > > > those is > > > > > > class Foo > > > def initialize(&blk) > > > @gen = blk > > > end > > > def value > > > @gen.call > > > end > > > end > > > > > > a = Foo.new { rand } > > > puts a.value > > > puts a.value > > > puts a.value > > > > Just try to implement: > > set_default(var, val) > > -- if variable "var" is not defined (not existed) then assign value > > "val" > > I think we have a stuck record here :-) > > For this particular example, the code you are looking for is: > > var ||= val > > with no method call at all. This is a tiny pattern and not worth > abstracting. > > Local variables are *static*. Local variables are not intended to be > handled > in the way you are asking. The language provides other facilities (i.e. > not > local variables) when you want to be more dynamic. > > "Doctor, it hurts when I do this." > "Then don't do that!" > > Try the following if you don't understand what I mean by local variables > being "static". > > def x > "This method is never called" > end > > if false > x = "Local variable" > end > > puts x > > This code prints "nil". Reflect on why this is the case. > > Regards, > > Brian. > > The "local variables" is exactly what confuses me. Why can't I use variables (read/set) inside of function that is at the same hierarchy as variable is? ------=_Part_12964_3070219.1173691859222--