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?
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.
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.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With