List comprehension in Ruby

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?


Solution 1:

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...

Solution 2:

If you really want to, you can create an Array#comprehend method like this:

class Array
  def comprehend(&block)
    return self if block.nil?
    self.collect(&block).compact
  end
end

some_array = [1, 2, 3, 4, 5, 6]
new_array = some_array.comprehend {|x| x * 3 if x % 2 == 0}
puts new_array

Prints:

6
12
18

I would probably just do it the way you did though.