Published on One Big Library. (http://onebiglibrary.net)
How to do pythonic list comprehensions with conditions in ruby?
By dchud
Created 2006-06-23 15:49

Python has an elegant syntax for taking all or part of a list and optionally transforming its values, should they meet zero or more conditions. It's called "list comprehensions", and looks like this:

In [1]: [x for x in range(10) if x % 2 == 0]
Out[1]: [0, 2, 4, 6, 8]

(...er, that's without the transformation part. But that's irrelevant for this question...)

I'm not finding a "simple" or "elegant" way of doing this in ruby, but maybe I just don't know where to look. The best I've found is this:

irb(main):031:0> (0..10).collect {|x| x unless x % 2 == 0} .compact
=> [1, 3, 5, 7, 9]

...which, shall we say, is inelegantly adequate. You have to add the .compact part to remove the

nil

s that will be left in otherwise:

irb(main):032:0> (0..10).collect {|c| c unless c%2==0}
=> [nil, 1, nil, 3, nil, 5, nil, 7, nil, 9, nil]

What's the better way? I'm hoping there is one...

Trackback URL for this post:

http://onebiglibrary.net/trackback/80

Source URL (retrieved on 2008-11-20 07:44): http://onebiglibrary.net/story/how-to-do-python-list-comprehensions-with-conditions-in-ruby