On Thu, 5 Sep 2002, Gavin Sinclair wrote:
> > def foo()
> > # do something
> > end
> >
> > def bar()
> > #do somehing
> > x = foo
> > # do something with x
> > end
You would lose the possibility to call a method without writing
parentheses.
> Why not def-within-def? It can make it clear that one method is merely a
> helper for another, while making use of lexical scoping.
It would be nice, but imho interferes with ruby's internals. Ruby has no
functions -- only methods. A nested def would make sense as a function
definition, but not as a method definition. (If it were a method, then a
method of which object? If it were a method of the object "self", then
why wouldn't I be able to call it by name from an external scope?)
> [... SICP, Scheme ...] but the book is great, and the language is
> instructional.
Yes! At least that's what I can tell while reading the second chapter.
> def sqrt(x)
> good_enough = lambda { |g1,g2| ((g1 - g2).abs / g2) < .001 }
> improve = lambda { |guess| average(guess, x/guess) }
> sqrt_iter = lambda { |g1,g2|
> (good_enough[g1,g2]) ? g2 : sqrt_iter[g2, improve[g2]]
> }
> sqrt_iter[1.0, 2.0]
> end
This just came to my mind: Since ruby allows for nested singleton
methods, you could probably write:
def sqrt(x)
o = Object.new
def o.good_enough(g1,g2)
((g1 - g2).abs / g2) < .001
end
def o.improve(guess)
average(guess, x/guess)
end
def o.sqrt_iter(g1,g2)
good_enough(g1,g2) ? g2 : sqrt_iter(g2, improve(g2))
end
o.sqrt_iter(1.0, 2.0)
end
and regard "o." as the syntax for defining and accessing nested functions.
Maybe someone can golf the o=Object.new away... the shortest replacements
that I can think of are o=[] and o={}.
Tobias