Skip to content

Instantly share code, notes, and snippets.

@MattMSumner
Created November 4, 2015 20:52
Show Gist options
  • Save MattMSumner/7ebf2d9496ea963f2d9a to your computer and use it in GitHub Desktop.
Save MattMSumner/7ebf2d9496ea963f2d9a to your computer and use it in GitHub Desktop.
matrix = [
[1,2,3,4,5],
[6,7,8,9,10],
[2,4,6,8,10],
[1,3,5,7,9],
[3,6,9,2,4]
]
matrix.each_with_index.inject({start_top_left: 0, start_top_right: 0}) do |hash_of_sums, (row, index)|
hash_of_sums[:start_top_left] += row[index]
hash_of_sums[:start_top_right] += row[-(index+1)]
hash_of_sums
end
@MattMSumner
Copy link
Author

each_with_index returns what is known as an enumerable. This is an object that you can iterate over and when you do, you'll be given each object in the enumerable plus the index. I'm then using inject to iterate over the matrix.

So I start with my matrix, which is an array of arrays. I then call each_with_index which sort of changes it to an array of arrays with indices. I then call inject on that. Inject will run the block of code for each array/index pair. The first argument is the thing that is passed between each run of the block of code. For the first run through, hash_of_sums will be the first argument to inject i.e. {start_top_left: 0, start_top_right: 0}. Every run after that, hash_of_sums will be whatever is returned from the block of code. That is why the last line of the block is just hash_of_sums to make sure it gets passed to the next run through.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment