List comprehension in Ruby

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

    I've just published the comprehend gem to RubyGems, which lets you do this:

    require 'comprehend'
    
    some_array.comprehend{ |x| x * 3 if x % 2 == 0 }
    

    It's written in C; the array is only traversed once.

提交回复
热议问题