The Javascript-Ruby Connection Slims #
Yeah, Ruby and Javascript have a close proximity—flgr once gave us proof. MenTaL spotted a list of additions to Javascript arrays, which reeks of the Ruby Way.
Of special note is the addition of forEach
, but just look how valuable the Ruby equivalents of these methods have become to us:
JS | Ruby |
indexOf |
index |
lastIndexOf |
rindex |
some |
any? |
every |
all? |
filter |
find_all |
forEach |
each |
map |
map |
Interesting. I’m reading here and each of the iterators sends three parameters to the “block”. The value, the current index and the array itself.
var aNumbers = [4, 2, 6, 9]; var aTimesTwoNumbers = aNumbers.map(function (v, i, ary) { return v * 2; });
It’s that index value. We’ve never known where to put it. I believe in Javascript you can safely omit parameters you’re not using. (via webref.)
flgr
Same for Ruby.JS. It always yields the index (which is the key for hashes) as well.
Expect more Ruby-like constructs to appear in JavaScript soon. Good stuff will happen.
eule
When are we finally going to translate Ruby into JS, making AJAX a seamless experience ?
mdaines
I was working on a Rails app with a lot of JavaScript at the front, and ran into this.
Neither FireFox or Safari seem to support these, (though I thought Firefox did? perhaps I’m mistaken.) and to put your own versions on the prototype of “Array” yourself is convenient but also doesn’t work for some cases. If you write something like this…
...it doesn’t work, because getElementsByTagName and the like don’t return an actual array, just an array-like object. (A live query, actually.) To fix that, I made a function called toArray and put it in Array. So now I do this:
I don’t know how harmful/not harmful all this is, but it works…
Also: I actually wrote “each” instead of “forEach” initially, and am making it forEach in my code even though I don’t like it because it’s less like Ruby. And in a way I feel a strange sense of pride writing “map(function(v) {” and then the “});” at the end. I guess “});” is a man with a big moustache winking at you or something.
mdaines
aha. having read the linked post, I see this is explained already! and toArray in Array is probably a bad idea.
fredrik
Putting a forEach method in the Nodelist prototype sounds like a much better idea. The same can be done for other methods from the Array object.
Ian Bicking
Mochikit introduces adapters and iterators to handle the issue of Array-like objects (that aren’t actually Arrays). The result is kind of Lispish, kind of Pythonish.
flgr
eule: Autrijus (the Pugs guy) was working on that last time I saw him.
Comments are closed for this entry.