Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension in Ruby

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 there a better way to do this...perhaps with one method call?

like image 341
readonly Avatar asked Nov 21 '08 22:11

readonly


People also ask

Does Ruby have list comprehension?

Even better, some things that are hard in Ruby are one-liners in Python with list comprehensions. So if you are a Rubyist trying to learn Python, here are some of the basics of list comprehensions explained side by side with equivalent Ruby.

Does Ruby have list?

As suggested by RBK above, List comprehension in Ruby provides a whole slew of different ways to do things sort of like list comprehensions in Ruby. None of them explicitly describe nested loops, but at least some of them can be nested quite easily.


2 Answers

How 'bout:

some_array.map {|x| x % 2 == 0 ? x * 3 : nil}.compact 

Slightly cleaner, at least to my taste, and according to a quick benchmark test about 15% faster than your version...

like image 98
glenn mcdonald Avatar answered Oct 06 '22 11:10

glenn mcdonald


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.

like image 37
Robert Gamble Avatar answered Oct 06 '22 11:10

Robert Gamble