Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby equivalent of python izip_longest [closed]

Tags:

python

ruby

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?

like image 217
skeept Avatar asked Oct 20 '25 03:10

skeept


1 Answers

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]]
like image 58
falsetru Avatar answered Oct 21 '25 16:10

falsetru