To do the equivalent of Python list comprehensions, I'm doing the following:
some_array.select{|x| x % 2 == 0 }.collect{|x| x * 3}
Is there a better way to do this...perhaps with one method call?
To do the equivalent of Python list comprehensions, I'm doing the following:
some_array.select{|x| x % 2 == 0 }.collect{|x| x * 3}
Is there a better way to do this...perhaps with one method call?
Enumerable has a
grep
method whose first argument can be a predicate proc, and whose optional second argument is a mapping function; so the following works:This isn't as readable as a couple of other suggestions (I like anoiaque's simple
select.map
or histocrat's comprehend gem), but its strengths are that it's already part of the standard library, and is single-pass and doesn't involve creating temporary intermediate arrays, and doesn't require an out-of-bounds value likenil
used in thecompact
-using suggestions.If you really want to, you can create an Array#comprehend method like this:
Prints:
I would probably just do it the way you did though.
How 'bout:
Slightly cleaner, at least to my taste, and according to a quick benchmark test about 15% faster than your version...
Something like this:
Call it:
Which returns:
I've just published the comprehend gem to RubyGems, which lets you do this:
It's written in C; the array is only traversed once.
That works for me. It is also clean. Yes, it's the same as
map
, but I thinkcollect
makes the code more understandable.actually looks better, after seeing it below.