Created
September 9, 2008 15:08
-
-
Save jmettraux/9689 to your computer and use it in GitHub Desktop.
an idea
This file contains 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
class RuleBook | |
def initialize (&block) | |
@rules = [] | |
add_rules(&block) | |
end | |
def add_rules (&block) | |
instance_eval(&block) if block | |
self | |
end | |
def eval (facts) | |
facts = Facts.new(facts) unless facts.is_a?(Facts) | |
@rules.each do |r| | |
if facts.instance_eval(&r[0]) | |
facts.instance_eval(&r[1]) | |
break | |
end | |
end | |
facts | |
end | |
protected | |
def rule (conditional, consequence) | |
@rules << [ conditional, consequence ] | |
end | |
# for the sake of sparing 5 chars | |
# | |
def l (&block) | |
lambda &block | |
end | |
end | |
class Facts | |
def initialize (h) | |
@hash = h | |
end | |
def method_missing (mname, *args) | |
mname = mname.to_s | |
@hash[mname] || mname | |
end | |
def set (k, v) | |
@hash[k] = v | |
end | |
end | |
my_rules = RuleBook.new do | |
rule( | |
l { color == 'blue' }, | |
l { set(nose, green) }) | |
rule( | |
l { color == red }, | |
l { set(count, 2) }) | |
rule( | |
l { color == purple and size == medium }, | |
l { puts 'murasaki no ue' }) | |
end | |
# | |
# if h['color'] = 'blue' then h['nose'] = 'green' | |
# if h['color'] = 'red' then h['count'] = 2 | |
# | |
# :( | |
# | |
p my_rules.eval('color' => 'blue') | |
p my_rules.eval('color' => 'red') | |
p my_rules.eval('color' => 'white') | |
p my_rules.eval('color' => 'purple') | |
p my_rules.eval('color' => 'purple', 'size' => 'medium') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment