Does Ruby have something like Python's list comprehensions? -


python has nice feature:

print([j**2 j in [2, 3, 4, 5]]) # => [4, 9, 16, 25] 

in ruby it's simpler:

puts [2, 3, 4, 5].map{|j| j**2} 

but if it's nested loops python looks more convenient.

in python can this:

digits = [1, 2, 3] chars = ['a', 'b', 'c']     print([str(d)+ch d in digits ch in chars if d >= 2 if ch == 'a'])     # => ['2a', '3a'] 

the equivalent in ruby is:

digits = [1, 2, 3] chars = ['a', 'b', 'c'] list = [] digits.each |d|     chars.each |ch|         list.push d.to_s << ch if d >= 2 && ch == 'a'     end end puts list 

does ruby have similar?

the common way in ruby combine enumerable , array methods achieve same:

digits.product(chars).select{ |d, ch| d >= 2 && ch == 'a' }.map(&:join) 

this 4 or characters longer list comprehension , expressive (imho of course, since list comprehensions special application of list monad, 1 argue it's possible adequately rebuild using ruby's collection methods), while not needing special syntax.


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c++ - Using OpenSSL in a multi-threaded application -

All overlapping substrings matching a java regex -