Skip to content

Instantly share code, notes, and snippets.

@tiagoefmoraes
Created February 13, 2015 18:20
Show Gist options
  • Save tiagoefmoraes/c10c07027ded0095f28a to your computer and use it in GitHub Desktop.
Save tiagoefmoraes/c10c07027ded0095f28a to your computer and use it in GitHub Desktop.
Define steps to process arrays in batches
def self.join(first, last)
if first.is_a?(Range) && last.is_a?(Range)
first.first..last.last
elsif first.is_a?(Range)
first.first..last
elsif first == last
first
else
first..last
end
end
def self.define_steps(a, by)
result = {}
remaining = a.to_a
while remaining.size > 1
remaining = remaining.each_slice(by).map do |slice|
result[slice] = join(slice.first, slice.last)
end
end
result.reject! {|k| k.size == 1}
end
a = 1..10
result = define_steps(a, 3)
expected = {[1, 2, 3] => 1..3,
[4, 5, 6] => 4..6,
[7, 8, 9] => 7..9,
[1..3, 4..6, 7..9] => 1..9,
[1..9, 10] => 1..10
}
if result == expected
puts 'ok'
puts result.values.last
else
p result
p expected
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment