开发者

"Ruby-ish" way of creating a new instance of a class with parameters from multiple arrays?

开发者 https://www.devze.com 2023-03-02 00:39 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消