单独的一个数组的数组被传递到作为多个对象的方法 [英] Separate an array of arrays to be passed into a method as multiple objects
问题描述
我有一个接受多个阵列,从此迈出了图示运营商的方法SO线程。
I have a method that accepts multiple arrays with a splat operator taken from this SO 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 an array of arrays:
my_array = [[1,2],[3,4],[5,6]]
我如何通过
interleave(my_array)
,使得它通过子阵列中分别?我似乎无法分离 my_array
(其中可能有几百个)放入单独的对象。
so that it passes the subarrays in separately? I can't seem to separate my_array
(of which there can be hundreds) into separate objects.
推荐答案
我想什么你试图做的可以用图示操作者在方法调用的时候,喜欢这类来完成:
What I think you're attempting to do can be accomplished by using the splat operator at the time of method invocation, like such:
hello(*my_array)
下面是一个完整的例子:
Here's a complete example:
def foo(a, *b)
puts a.inspect
puts b.inspect
end
foo(*[[1, 2], [3, 4], [5, 6]])
打印以下内容:
[1, 2]
[[3, 4], [5, 6]]
编辑:其他的解决方案
现在,您已经粘贴源我的看法是,该方法应该重新写入采取单一的参数,而不是在参数的使用图示操作者拉出第一
和其他
。其原因是,如果在运行时的多维数组的长度发生变化,你会更好拉出第一
和其他
里面的方法,所以你不必到处使用的图示。
Now that you've pasted the source my opinion is that the method should be re-written to take a single parameter instead of using the splat operator in the parameters to pull out the first
and rest
. The reason is that if the length of the multidimensional array changes at runtime you'd be better off pulling out first
and rest
inside the method so you're not having to use the 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]])
这篇关于单独的一个数组的数组被传递到作为多个对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!