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?
I made a quick benchmark comparing the three alternatives and map-compact really seems to be the best option.
Performance test (Rails)
Results
Another solution but perhaps not the best one
or
An alternative solution that will work in every implementation and run in O(n) instead of O(2n) time is:
I think the most list comprehension-esque would be the following:
Since Ruby allows us to place the conditional after the expression, we get syntax similar to the Python version of the list comprehension. Also, since the
select
method does not include anything that equates tofalse
, all nil values are removed from the resultant list and no call to compact is necessary as would be the case if we had usedmap
orcollect
instead.This is more concise:
Like Pedro mentioned, you can fuse together the chained calls to
Enumerable#select
andEnumerable#map
, avoiding a traversal over the selected elements. This is true becauseEnumerable#select
is a specialization of fold orinject
. I posted a hasty introduction to the topic at the Ruby subreddit.Manually fusing Array transformations can be tedious, so maybe someone could play with Robert Gamble's
comprehend
implementation to make thisselect
/map
pattern prettier.