Ruby-like blocks and iterators in JavaScript

Posted by Daniel on January 19, 2008
Programming

Ruby is a wonderful language, I love it. I so wish that it was more widely deployed than it is, but with the recent success of Ruby on Rails the situation might improve. Anyways, one thing I miss about Ruby is its blocks and iterators:

5.times {|count| puts count }

array = [1, "hi", 3.14]
array.each { |item| puts item }

While I don’t think you can get the full expressive power of Ruby blocks and iterators in JavaScript, you can definitely get some of it:

Number.prototype.times = function(fn){
     for(var i=0; i<this; i++) fn(i);
};
Array.prototype.each = function(fn) {
     for (var i=0; i<this.length; i++) fn(this[i]);
};

Now we can do this:

/* Notice that we need brackets around the 5. */
(5).times(function(count){
     document.write(count+"<br/>");
});
["Alice","Bob","Eva"].each(
     function(name) {document.write("Hello "+name+"<br/>")}
);

Not quite Ruby, but pretty neat anyways. Just be careful when extending base classes like this; make sure that there aren’t any conflicts. If you think this is cool, take a look at ruby.js from Florian Gross.

Note: Be careful when using libraries that extend base classes (like ruby.js and Prototype). As cool as they are, they create a risk of conflict with your code or other libraries.

Mozilla’s JavaScript 1.6 includes an Array:forEach method, but this is not part of ECMAScript and should not be expected to work in all browsers.

No comments yet.

Leave a comment

WP_Big_City

xanax 2mg