List comprehension in Ruby

Readonly picture Readonly · Nov 21, 2008 · Viewed 47.9k times · Source

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?

Answer

glenn mcdonald picture glenn mcdonald · Nov 22, 2008

How 'bout:

some_array.map {|x| x % 2 == 0 ? x * 3 : nil}.compact

Slightly cleaner, at least to my taste, and according to a quick benchmark test about 15% faster than your version...