On Mar 12, 7:47 pm, Brian Candler <B.Cand... / pobox.com> wrote:
> On Mon, Mar 12, 2007 at 05:16:08PM +0900, Sebastian Hungerecker wrote:
> > ara.t.how... / noaa.gov wrote:
> > > On Mon, 12 Mar 2007, Mike wrote:
> > > > I was talking more about macros rather then constants.  But I agree that
> > > > constant are convenient way to substitute "#define myconst 15". But can
> > > > you substitute "#define myfunc(x) (sin(x)*cos(x)*exp(x))"?  You should
> > > > know that "x" could be as much other functions as a constant/variable.
>
> > > perhaps i'm being dense, but i fail to see how the above example is none
> > > other than a simple function in ruby:
>
> > Imagine you would call the function with rand() as parameter. With #define
> > rand would be called three times, with def it would be called once and its
> > 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"