O Ruby tem algo parecido com as compreensões da lista do Python?
Python tem um ótimo recurso:
print([j**2 for j in [2, 3, 4, 5]]) # => [4, 9, 16, 25]
Em Ruby é ainda mais simples:
puts [2, 3, 4, 5].map{|j| j**2}
mas se é sobre loops aninhados Python parece mais conveniente.
Em Python podemos fazer isso:
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']
O equivalente em Ruby é:
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
O Ruby tem algo parecido?