Search code examples
rubylist-comprehension

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

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