tisdag, augusti 14, 2007

Comprehensions in Ruby

Now, this is totally awesome. Jay found a way to implement generic comprehensions in Ruby. In twenty lines of code. It's really quite obvious when you look at it. An example:
(1..100).find_all &it % 2 == 0
%w'sdfgsdfg foo bazar bara'.sort_by(&its.length).map &it.reverse.capitalize

%w'sdfgsdfg foo bazar bara'.map &:to_sym
%w'sdfgsdfg foo bazar bara'.map &it.to_sym
Now, the last two lines are what I like the most. The Symbol to_proc tric is widely used, but I actually think the comprehension version is more readable. It's even better if replacing "map " with "collect".

This is actually real fun. You can link how many methods you like - you can send arguments to the methods, you can send blocks to them, you can link and nest however you want. It apples for Arrays, Sets, Hashes - everything you can send a block to can use this, so it's not limited to collections or anything like that.

I think it's really, really cool, and it should be part of Facets, ActiveSupport, hell, the Ruby core library. I want it there.

Now, the only, only, only quibble I have with it... He choose to call it "The Methodphitamine". You should actually use 'require "methodphitamine"'. It's a gem. I love it. But I hate the name. So, read more in his blog, here: http://jicksta.com/articles/2007/08/04/the-methodphitamine.

6 kommentarer:

Anonym sa...

Seems like _why blogged about this a while ago... and who knows, probably someone before that!

Lambda Camcorder

Ola Bini sa...

Ah, you're totally right. It seems it's not new, after all.

Anonym sa...

Yet another take on it: http://snippets.dzone.com/posts/show/3277

Anonym sa...

I don't think it'll ever be included in Ruby core.

The biggest reason is that it's not entirely transparent. Imagine a situation where you're trying to find all to_proc'able items in a list.

[1,:2].select &it.respond_to?(:to_proc)

This won't work like you expect, due to the implementation.

Jay sa...

No way! Someone else HAS done it before. Sheesh.

Oh well. I think the Methodphitamine's implementation looks a bit nicer and bundling it a gem adds the ability for something like this to catch on.

Props to Mike Williams for beating me to it. :)

Jay Phillips

Daniel Berger sa...

Truly awful notation. Instead of pretending that Symbol#to_proc is a generic metaprogramming solution, let's just allow Enumerable methods to take arguments, which is what everyone is using them for in practice.