Skip to content

Instantly share code, notes, and snippets.

@hawx
Created September 19, 2010 13:51
Show Gist options
  • Save hawx/586773 to your computer and use it in GitHub Desktop.
Save hawx/586773 to your computer and use it in GitHub Desktop.
# Matches an Array (of trues and falses) to a given Array. Fills itself
# with preference to fill where true first, then any spare items are put
# in place of false, then nils are used for remaining falses.
#
# input = ["a", "b", "c"]
# match = [true, false, false, true]
#
# match.optimise_fill(input)
# #=> ["a", "b", nil, "c"]
#
class Array
def optimise_fill(input)
match = self
diff = input.size - match.reject{|i| i == false}.size
result = []
match.each_index do |i|
curr_item = match[i]
if curr_item == true
result << input.shift
else
if diff > 0
result << input.shift
diff -= 1
else
result << nil
end
end
end
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment