List comprehension in Ruby

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

    Enumerable has a grep method whose first argument can be a predicate proc, and whose optional second argument is a mapping function; so the following works:

    some_array.grep(proc {|x| x % 2 == 0}) {|x| x*3}
    

    This isn't as readable as a couple of other suggestions (I like anoiaque's simple select.map or histocrat's comprehend gem), but its strengths are that it's already part of the standard library, and is single-pass and doesn't involve creating temporary intermediate arrays, and doesn't require an out-of-bounds value like nil used in the compact-using suggestions.

提交回复
热议问题