4

I know two arrays can be zipped and the result can be iterated with #each. But how do you do it with an unknown number of enumerables? Let's say

anand = %w(1-0 0.5-0.5 0.5-0.5 1.0)
carlsen = %w(0-1 0.5-0.5 0.5-0.5 1.0)
kramnik = %w(0.5-0.5 0.5-0.5 0.5-0.5 1.0)
players= [anand, carlsen, kramnik]
#something smart

players.each{|round|puts round} #first line should be  "1-0 0-1 0.5-0.5" 
2
  • Why can't you use a while loop and a plain old index variable? Commented Apr 10, 2010 at 22:28
  • @HamishGrubijan: Because using while-loops is more error prone and more verbose than using plain old higher-order functions. Commented Apr 10, 2010 at 22:41

2 Answers 2

9
players.transpose.map {|a| a.join(" ")}
Sign up to request clarification or add additional context in comments.

Comments

4
anand.zip(carlsen, kramnik) do |round| puts round.join(" ") end

This will print:

1-0 0-1 0.5-0.5
0.5-0.5 0.5-0.5 0.5-0.5
0.5-0.5 0.5-0.5 0.5-0.5
1.0 1.0 1.0

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.