Searching for range overlaps in Ruby hashes

Posted by mbm on Stack Overflow See other posts from Stack Overflow or by mbm
Published on 2010-12-22T20:14:43Z Indexed on 2010/12/22 20:54 UTC
Read the original article Hit count: 165

Filed under:
|

Say you have the following Ruby hash,

hash = {:a => [[1, 100..300],
               [2, 200..300]],
        :b => [[1, 100..300], 
               [2, 301..400]]
       }

and the following functions,

def overlaps?(range, range2)
  range.include?(range2.begin) || range2.include?(range.begin)
end

def any_overlaps?(ranges)
  # This calls to_proc on the symbol object; it's syntactically equivalent to 
  # ranges.sort_by {|r| r.begin} 
  ranges.sort_by(&:begin).each_cons(2).any? do |r1, r2|
    overlaps?(r1, r2)
  end
end

and it's your desire to, for each key in hash, test whether any range overlaps with any other. In hash above, I would expect hash[:a] to make me mad and hash[:b] to not.

How is this best implemented syntactically?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about hash