Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
# Objective: Split the alphabet in half.
# Here's our range of letters.
letters = ('a'..'z').to_a
# Because we know what all the letters in the alphabet is,
# and subsequently what the middle letter actually is, we can
# use the handy Enumerable#partition method to achieve the results
# we're after.
letters.partition { |letter| letter <= 'm' }
# => [
# ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"],
# ["n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
# ]
# However, what if we didn't know what the contents we were splitting is
# and instead we just want to split the contents in two equal parts.
# For this we might want to do something like the following:
output = [[], []]
midpoint = (letters.length - 1) / 2
letters.each_with_index do |letter, i|
output[0] << letter if i <= midpoint
output[1] << letter if i > midpoint
end
output
# => [
# ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"],
# ["n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
# ]
# You might be tempted to try and refactor that output array out of the mix
# by using inject, however, then you lose the ability to have the index of
# current iteration. As such, each_with_index is really the only option.
#
# Or is it? As of Ruby 1.8.7 (I believe), you can chain "with_index" onto
# enumerable method which will add the with_index behavior to that method's
# output. For example:
letters.partition.with_index { |letter, i| i <= midpoint }
# => [
# ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"],
# ["n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
# ]
# This gets us exactly what we were after from the start. Partitioning
# the array, but also having access to the iteration we're on. Good stuff!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment