ruby - Separate an array of arrays to be passed into a method as multiple objects -
ruby - Separate an array of arrays to be passed into a method as multiple objects -
i have method accepts multiple arrays splat operator taken thread.
def interleave(a,*args) max_length = args.map(&:size).max padding = [nil]*[max_length-a.size, 0].max (a+padding).zip(*args).flatten.compact end
i have array of arrays:
my_array = [[1,2],[3,4],[5,6]]
how pass
interleave(my_array)
so passes subarrays in separately? can't seem separate my_array
(of there can hundreds) separate objects.
what think you're attempting can accomplished using splat operator @ time of method invocation, such:
hello(*my_array)
here's finish example:
def foo(a, *b) puts a.inspect puts b.inspect end foo(*[[1, 2], [3, 4], [5, 6]])
prints following:
[1, 2] [[3, 4], [5, 6]]
edit: other solution
now you've pasted source sentiment method should re-written take single parameter instead of using splat operator in parameters pull out first
, rest
. reason if length of multidimensional array changes @ runtime you'd improve off pulling out first
, rest
within method you're not having utilize splat everywhere.
def interleave(args) a, *args = args max_length = args.map(&:size).max padding = [nil]*[max_length-a.size, 0].max (a+padding).zip(*args).flatten.compact end foo([[1, 2], [3, 4], [5, 6]])
ruby arrays
Comments
Post a Comment