Each

If there’s one thing I love about Ruby (beyond its design overall), it’s definitely iterators. Martin “fitting last name” Traverso implemented iterators in Java for fun some 19 months ago (yes, I’m fast) and here’s how they roll:

EnumerableCollection<Integer> list = new EnumerableArrayList<Integer>();

list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);

list.each(new IterationCallback<Integer>() {
     public void call(Integer element) {
         System.out.println(element);
     }
});

That’s a lot of typing, and I don’t mean on a keyboard. Here’s the translated Ruby version:

list = Array.new

list.push(1)
list.push(2)
list.push(3)
list.push(4)
list.push(5)

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

and here’s the “real”, not-writing-Java-in-Ruby Ruby version:

list = []

(1..5).each {|i| list << i}

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

So if you ever wonder why I would rather not program in Java (and apparently I’m not alone), that’s your answer.

Comments [+]

  1. Or, in Python: list(xrange(1, 6))

    By Peter Hosey · 2006.09.23 11:53

  2. (Or range(1, 6), but that’s cheating ;)

    By Peter Hosey · 2006.09.23 11:54

  3. Well, while we’re redefining the assignment:

    (1..6).to_a

    By Jesper · 2006.09.23 20:22

  4. Of course, you could’ve just gone

    (1..5).each {|i| puts i.to_s }

    and been done with it :)

    However it still nicely illustrates just how much “cleaner” it feels to write ruby.

    By PatrickQG · 2006.09.23 20:35

  5. Yes, duh, but anything else would have been an unfair comparison (which is why I included both “writing-Java-in-Ruby Ruby” and “pure Ruby”).

    By Jesper · 2006.09.24 00:05

  6. Oh, I see. The challenge was to print every element, not simply to build the list.

    In Python: for i in xrange(1, 6): print i

    I like that a lot better than the Ruby version.

    By Peter Hosey · 2006.10.22 08:59

Leave a comment

Your e-mail address is never shown. If you type a line break in the comment, it will show up as a line break (naturally). The following HTML is allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(required)

(required)


Please note: Your comment will not show up at once. Unless you're spamming or being abusive, you have nothing to worry about. (Read the full policy.)