class RangeMap
A map that stores ranges and their associated values for efficient lookup.
Definitions
def initialize
Initialize a new RangeMap.
Implementation
def initialize
@ranges = []
end
def add(range, value)
Add a range-value pair to the map.
Signature
-
parameter
range
Range
The range to map.
-
parameter
value
Object
The value to associate with the range.
-
returns
Object
The added value.
Implementation
def add(range, value)
@ranges << [range, value]
return value
end
def find(key)
Find the value associated with a key within any range.
Signature
-
parameter
key
Object
The key to find.
-
yields
{...}
Block called if no range contains the key.
-
returns
Object
The value if found, result of block if given, or nil.
Implementation
def find(key)
@ranges.each do |range, value|
return value if range.include?(key)
end
if block_given?
return yield
end
return nil
end
def each
Iterate over all values in the map.
Signature
-
yields
{|value| ...}
Block called for each value.
-
parameter
value
Object
The value from the range-value pair.
-
parameter
Implementation
def each
@ranges.each do |range, value|
yield value
end
end
def clear
Clear all ranges from the map.
Implementation
def clear
@ranges.clear
end