Class: Boolean::Expression
- Inherits:
-
Object
- Object
- Boolean::Expression
show all
- Defined in:
- lib/boolean/expression.rb
Defined Under Namespace
Classes: Group, Logic, Name
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(base = Group.new) ⇒ Expression
Returns a new instance of Expression.
83
84
85
|
# File 'lib/boolean/expression.rb', line 83
def initialize (base = Group.new)
@base = base
end
|
Instance Attribute Details
#base ⇒ Object
Returns the value of attribute base.
81
82
83
|
# File 'lib/boolean/expression.rb', line 81
def base
@base
end
|
Class Method Details
.[](*args) ⇒ Object
77
78
79
|
# File 'lib/boolean/expression.rb', line 77
def self.[] (*args)
parse(*args)
end
|
.parse(text) ⇒ Object
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
# File 'lib/boolean/expression.rb', line 25
def self.parse (text)
base = Group.new
name = nil
stack = [base]
logic = nil
text.to_s.chars.each_with_index {|char, index|
begin
if char == ')' && stack.length == 1
raise SyntaxError, 'closing an unopened parenthesis'
end
if char.match(/\s|\(|\)/) || (!logic && ['|', '&', '!'].member?(char))
if logic || (name && name.match(/(and|or|not)/i))
stack.last << Logic.new(logic || name)
logic = nil
name = nil
elsif name
stack.last << Name.new(name)
name = nil
end
end
if name || logic
name << char if name
logic << char if logic
else
case char
when '(' then stack.push Group.new
when ')' then stack[-2] << stack.pop
when '|' then logic = '|'
when '&' then logic = '&'
when '!' then stack.last << Logic.new('!')
else name = char if !char.match(/\s/)
end
end
rescue SyntaxError => e
raise "#{e.message} near `#{text[index - 4, 8]}` at character #{index}"
end
}
raise SyntaxError, 'not all parenthesis are closed' if stack.length != 1
raise SyntaxError, 'the expression cannot end with a logic operator' if logic
base << Name.new(name) if name
base = base.first if base.length == 1 && base.first.is_a?(Group)
new(base)
end
|
Instance Method Details
#evaluate(*args) ⇒ Object
Also known as:
[]
87
88
89
90
91
|
# File 'lib/boolean/expression.rb', line 87
def evaluate (*args)
_evaluate(@base, args.flatten.compact.map {|piece|
piece.to_s
})
end
|
#to_s ⇒ Object
95
96
97
|
# File 'lib/boolean/expression.rb', line 95
def to_s
@base.inspect
end
|