List comprehension in Ruby

后端 未结 17 2142
广开言路
广开言路 2020-12-02 07:01

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 ther

相关标签:
17条回答
  • 2020-12-02 07:53

    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.

    0 讨论(0)
  • 2020-12-02 07:55

    An alternative solution that will work in every implementation and run in O(n) instead of O(2n) time is:

    some_array.inject([]){|res,x| x % 2 == 0 ? res << 3*x : res}
    
    0 讨论(0)
  • 2020-12-02 07:55

    This is more concise:

    [1,2,3,4,5,6].select(&:even?).map{|x| x*3}
    
    0 讨论(0)
  • 2020-12-02 07:55

    https://rubygems.org/gems/ruby_list_comprehension

    shameless plug for my Ruby List Comprehension gem to allow idiomatic Ruby list comprehensions

    $l[for x in 1..10 do x + 2 end] #=> [3, 4, 5 ...]
    
    0 讨论(0)
  • 2020-12-02 07:58

    I think the most list comprehension-esque would be the following:

    some_array.select{ |x| x * 3 if x % 2 == 0 }
    

    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 to false, all nil values are removed from the resultant list and no call to compact is necessary as would be the case if we had used map or collect instead.

    0 讨论(0)
提交回复
热议问题