Search code examples
rubyhash

Searching for range overlaps in Ruby hashes


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?


Solution

  • hash.each{|k, v| puts "#{k} #{any_overlaps?( v.map( &:last )) ? 'overlaps' : 'is ok'}."}
    

    output:

    a overlaps.
    b is ok.