Felipe Almeida Felipe Almeida - 1 year ago 74
Ruby Question

How to recurse through arrays in Ruby

I'm trying to use the two following methods to recursively traverse arrays of arrays until the bottom and then come back up with the match results.

You know how in a tennis tournament they start with 32 matches and pair by pair the winner moves ahead, and at the end there's only one winner? That's what I want to replicate in Ruby.

I created a

that always returns the first array for the sake of simplicity. Then, I send the whole tournament array into
that calls itself recursively until it finds a simple array corresponding to a single match.

def match_winner(array_of_arrays)
return array_of_arrays[0]

def winner(tournament)
if tournament[0][0].is_a?(String)
return match_winner(tournament)

tournament = [
[["one", "two"],["three", "four"]],
[["five", "six"],["seven", "eight"]]

puts winner(tournament).inspect

Which outputs:

[[["one", "two"], ["three", "four"]], [["five", "six"], ["seven", "eight"]]]

I tried different permutations and variations on this algorithm but I couldn't make it work correctly and return only the final winner.

Does anyone see anything obviously wrong here?

Now I'm calling

Answer Source

Looks like you want map, not each, and, as a commenter above notes, you didn't call winner in the above code.

When you call:

tournament.each {...}

that method actually returns the tournament, which is thus what winner returns.

What you want is to replace it with

tournament.map {...}

which returns a new array consisting of calling "winner" on each element of tournament.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download