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

Re: Ruby and OO (fwd)

> Quite honestly, I would never guess that the following fragments come from
> the same language:
> - upto(100) { |i| puts i }
> - print ARGF.grep /Ruby/
> - @numMeetings.times { twoRatsMeet if moreThanOneRatLeft }
> I honestly can't figure out what any of these fragments means at a deep
> level.  For example,
>   - Why isn't the first 100.upto { |i| puts i }

Like any language you have to spend a little time looking at the
syntax in order to understand it. The syntax is "1.upto(100)" instead
of "100.upto" because you want to count from 1 to 100, you could as
easily do "x.upto(y)" where x and y are variables.  "x.upto(y) { |i|
.. }" is equivalent to "for (i=x;  x<=y; i++) { ... }"  Numeric types
(objects) have an upto method (and others) so you don't need for
loops. In ruby, iterators are implemented using blocks and are used

>   - What's with the vertical bars around the i?

Thats how you delminate the loop variable.

>   - What's the "receiver" for puts?

"puts" is a print statement. maybe this is more clear:

10.upto(100) { |i|
	puts i

will print 10 to 100. Check out more on blocks. "puts i" is actually a
block of code which is being passed to the upto method. Understanding
ruby iterators is not as easy as understanding java iterators, but
they are more powerful. imho this is a clunky way to print out a list
of integers:

for (ListIterator li = alist.listIterator(); i.hasNext();) {
	Integer i = (Integer)li.next();

in ruby this is:

list.each { |i|
	puts i

This, to me, is easier to read. This is of course one of the nice
things about scripting languages (the perl and python are similar
though not oo, not that oo is the end all be all, its just the way
ruby does things).

>   - What's the "receiver" for print?

print is similar to puts

>   - What on earth is "@"?

This deliminates a class member variable. Here's an example class:

class SomeObject
  attr_reader :memberVar
  attr_writer :memberVar

  def initialize()
    @memberVar = 10

  def isMemberVarBig?
    return @memberVar > 100

attr_read/writer is an easier way of defining getters/setters. the
second method is the same as a getter, it just illustrates using the
member variable (you don't need to write the return because the
value of the last expression executed is always returned).

>   - 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

> Some people also think that terseness in the language is a feature.
> I myself don't buy that.  I don't believe in verbose, either, as it happens.

I think terseness is a feature only if it makes the code easier to
read. To me terseness/verbocity is not the issue, ease of reading is.

-- Eli