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.
Or, in Python:
list(xrange(1, 6))By Peter Hosey · 2006.09.23 11:53
(Or
range(1, 6), but that’s cheating ;)By Peter Hosey · 2006.09.23 11:54
Well, while we’re redefining the assignment:
(1..6).to_aBy Jesper · 2006.09.23 20:22
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
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
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 iI like that a lot better than the Ruby version.
By Peter Hosey · 2006.10.22 08:59