I am trying to learn ruby. At this moment I have a list of lists, and I would like to the equivalent of the following python code:
import itertools
l = [[1,2], [3], [10, 20, -4, 5]]
list(itertools.izip_longest(*l, fillvalue='NaN'))
The result is:
[(1, 3, 10), (2, 'NaN', 20), ('NaN', 'NaN', -4), ('NaN', 'NaN', 5)]
The number of lists in the list l
can be different. Is there a easy way of accomplishing the same in ruby?
I don't think there is a direct counterpart for izip_longest
in Ruby standard library.
l = [[99,2], [3], [10, 20, -4, 5]]
n = l.map{ |x| x.size }.max
(0...n).map { |i| l.map { |x| x.fetch(i, 'NaN') } }
# => [[99, 3, 10], [2, "NaN", 20], ["NaN", "NaN", -4], ["NaN", "NaN", 5]]
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