Skip to content

Instantly share code, notes, and snippets.

@btelles
Created January 23, 2010 20:01
Show Gist options
  • Save btelles/284765 to your computer and use it in GitHub Desktop.
Save btelles/284765 to your computer and use it in GitHub Desktop.
Split a hash into multiple equal-sized hashes
# Extend hashes by adding one method that allows you to split a hash into an array of equal-sized hashes.
# Filter items to be included in the result by adding a selecting block that returns true
# if the key/value is to be kept.
# Per the usage example, return values are not ordered unless you're using Ruby 1.9
# usage:
# a = {1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 5 => 'e'}
# a.split_into(3) {|k,v| k.instance_of?(Integer)}
# => [{5=>"e", 3=>"c"}, {1=>"a", 4=>"d"}, {2=>"b"}]
Hash.class_eval do
def split_into(divisions, &:block)
count = 0
inject([]) do |final, key_value|
if !block_given? || yield(key_value[0], key_value[1])
final[count%divisions] ||= {}
final[count%divisions].merge!({key_value[0] => key_value[1]})
count += 1
end
final
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment