Skip to content

Instantly share code, notes, and snippets.

@burtlo
Created January 14, 2011 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burtlo/779228 to your computer and use it in GitHub Desktop.
Save burtlo/779228 to your computer and use it in GitHub Desktop.
Return the value that matches the most restrictive set or just return the default value
require 'set'
class SuperSet
def initialize(default)
@default = default
@hash = Hash.new
end
def ask(terms)
return @default if terms.nil? || terms.empty?
t = @hash.find_all{|a,b| a.superset?(Set.new(terms)) }
t.sort!{|a,b| a.first.superset?(b.first) ? 1 : -1 } if t
(t && !t.empty?) ? t.first.last : @default
end
def add(value,terms)
@hash[Set.new(terms)] = value
end
end
s = SuperSet.new :clone
s.add(:luke,[:jedi])
s.add(:vader,[:jedi,:father])
puts "luke ?= #{s.ask([:jedi])}"
puts "vader ?= #{s.ask([:jedi,:father])}"
puts "clone ?= #{s.ask([:wookie])}"
puts "clone ?= #{s.ask([])}"
puts "clone ?= #{s.ask(nil)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment