[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Ruby and OO (fwd)

Eli doesn't say who he's responding to here, but there are a few magic 
words that might help his explanations... (caveat: Everything I learned
about Ruby, I got from reading those online powerpoint slides---which
were very well done, by the way; my usual complaint about new languages
is that I have to spend so much time learning the syntax that I can't
get into the semantics, but these slides introduced the syntax in a good
order such that even without much explanation I think I got most of the

Quoth Eli Collins:
> >   - What's with the vertical bars around the i?
> Thats how you delminate the loop variable.
> [...]
> "puts" is a print statement. maybe this is more clear:
> 10.upto(100) { |i|
> 	puts i
> }

The vertical bars are just a binding construct, and a "block" is just a
closure---that one might be rewritten as

  (lambda i (puts i))

There is a separate syntax in ruby for defining a function with a name
(as there has to be, for recursion to work), but this block syntax seems
to be pretty pervasive; most functions (er, methods) implicitly take a
block argument to which they will pass a series of values---these
methods are called "iterators", and they "yield" these successive values
to their "receivers", but aside from the unfamiliar terminology it seems
to all be pretty straightforward stuff.

> list.each { |i|
> 	puts i
> }

Here, there is a method "each" in the object "list" (or rather, in the
class to which "list" belongs; this method accepts a procedure and
passes each successive value of the list into the procedure.  This
Scheme code would seem to be exactly equivalent (modulo the fact I've
had to name the method "List-each" instead of "each", and the variable
"lst" instead of "list"):

(List-each lst (lambda (i) (puts i))

These blocks definitely seem to be closures, by the way---one of the
slides online shows an example that either demonstrates closure or
dynamic scope, so I'm going to assume the former. :)

> >   - I guess I understand the 'if', maybe...
> >
> > I read the introductory material and didn't feel any more enlightened,
> > quite honestly.  Of course, I never could read Smalltalk, either...
> To each their own :)  Ruby definetly goes about doing some things
> differently.

It certainly makes more use of anonymous closures than any of the other
non-functional languages I've seen (though admittedly I haven't yet
grokked smalltalk either).

-=-Don Blaheta-=-=-dpb@cs.brown.edu-=-=-<http://www.cs.brown.edu/~dpb/>-=-
"These conditions can signify one of two things: (1) some horrible
disease, trauma, or other problem, or (2) nothing."	--Cecil Adams