List comprehension in Ruby

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

    There seems to be some confusion amongst Ruby programmers in this thread concerning what list comprehension is. Every single response assumes some preexisting array to transform. But list comprehension's power lies in an array created on the fly with the following syntax:

    squares = [x**2 for x in range(10)]
    

    The following would be an analog in Ruby (the only adequate answer in this thread, AFAIC):

    a = Array.new(4).map{rand(2**49..2**50)} 
    

    In the above case, I'm creating an array of random integers, but the block could contain anything. But this would be a Ruby list comprehension.

提交回复
热议问题