"Ruby-ish" way of creating a new instance of a class with parameters from multiple arrays?
What is the "ruby-ish" wa开发者_JS百科y of creating a new instance of a class with parameters from multiple arrays, at the same index location in the arrays?
For example, I'm currently doing:
array1.each_with_index { |element, i|
MyClass(element, array2[i], array3[i], array4[i])
}
This works fine, but I don't feel this is ruby-ish. Is there another way to do this in Ruby?
-- Derek
[array1, array2, array3, array4].transpose.map{|args| MyClass(*args)}
array1.zip(array2, array3, array4){|args| MyClass(*args) }
But be careful with different array sizes - like in your example, it will throw away array elements of array2-4, if they are longer than array1.
精彩评论