2

What is the "ruby-ish" way 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

2 Answers 2

5
[array1, array2, array3, array4].transpose.map{|args| MyClass(*args)}
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.