Skip to content

Instantly share code, notes, and snippets.

@devsigner
Created September 4, 2014 13:06
Show Gist options
  • Save devsigner/d355e6d277c46352028b to your computer and use it in GitHub Desktop.
Save devsigner/d355e6d277c46352028b to your computer and use it in GitHub Desktop.
#---------------------
# how to use:
# h = range_hash({})
# h[1..3] = 'v1'
# h[8..12] = 'v2'
# h #=> { 1..3 => 'v1', 8..12 => 'v2' }
#
# h[2..5] #=> 'v1'
# h[4..6] #=> nil
# h[5] #=> 'v2'
#
def range_hash hash
Hash.new { |this_hash,missing_key|
found_key = this_hash.keys.find { |this_key|
this_key.is_a?(Range) &&
(
( missing_key.is_a?(Integer) && (this_key.include?(missing_key)) ) ||
( missing_key.class == Range && (missing_key.to_a & this_key.to_a).present? )
)
}
found_key ? this_hash[found_key] : nil
}.merge(hash)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment