List comprehension in Ruby

后端 未结 17 2145
广开言路
广开言路 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:42

    Ruby 2.7 introduced filter_map which pretty much achieves what you want (map + compact):

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

    You can read more about it here.

提交回复
热议问题