From: Gavin Sinclair Date: 2002-09-06T10:30:00+09:00 Subject: Re: Ruby aesthetics [From Tobias:] > >> 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?) Yes, I thought this might be the case. I didn't leave it there, though, because I remember gcc adds nested function definitions to C, and presumably allows them in C++. A def-within-def would only be a function, because it's only available to the method that defines it. This "messing with Ruby's internals" would not be worth doing, IMO. >> [... 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. Gees, I haven't made it that far yet... >> 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 That's a nice one. I'll probably play with that and see how it goes. I'll just point out again that this is for mucking around with Scheme and Ruby, not for serious Ruby programming! > 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={}. I think creating a new Object is clearer. If I see someone declare a new array, I damn well expect to see them use it as one. > Tobias Cheers, Gavin