Hat Ruby so etwas wie Pythons Listenverständnis?

Python hat eine nette Funktion:

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

In Ruby ist es noch einfacher:

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

Aber wenn es um verschachtelte Schleifen geht, sieht Python praktischer aus.

In Python können wir dies tun:

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

Das Äquivalent in Ruby ist:

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

Hat Ruby etwas ähnliches?

Antworten auf die Frage(3)

Ihre Antwort auf die Frage