Created
January 14, 2011 05:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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