Skip to content

Instantly share code, notes, and snippets.

@devsigner
Created November 28, 2015 17:11
Show Gist options
  • Save devsigner/7e83d7a31f206a5a50c9 to your computer and use it in GitHub Desktop.
Save devsigner/7e83d7a31f206a5a50c9 to your computer and use it in GitHub Desktop.
Ruby Hash with Range key
# Hash with range keys
#---------------------
# ex:
# h = range_hash({})
# h[1..3] = 'v1'
# h[8..12] = 'v2'
#=> { 1..3 => 'v1', 8..12 => 'v2' }
#
# h[2..5] #=> 'v1'
# h[4..6] #=> nil
# h[5] #=> 'v2'
#
def range_hash hash
@ranges = 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