Class: Extract::MathWrapper
- Includes:
- FromHash
- Defined in:
- lib/extract/math_calc.rb
Instance Attribute Summary collapse
-
#str ⇒ Object
Returns the value of attribute str.
Instance Method Summary collapse
- #apply(l, r) ⇒ Object
- #left_associative? ⇒ Boolean
- #operator? ⇒ Boolean
- #precedence ⇒ Object
- #to_s ⇒ Object
Instance Attribute Details
#str ⇒ Object
Returns the value of attribute str.
6 7 8 |
# File 'lib/extract/math_calc.rb', line 6 def str @str end |
Instance Method Details
#apply(l, r) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/extract/math_calc.rb', line 18 def apply(l,r) #puts "apply call #{l} #{str} #{r}" raise "bad apply, not an operator" unless operator? #raise "bad apply, L #{l} R #{r}" unless l.to_s.present? && r.to_s.present? l.str = "0" if l.respond_to?(:str) && l.str.blank? r.str = "0" if r.respond_to?(:str) && r.str.blank? op = str op = "**" if op == "^" exp = "#{l.to_s} #{op} #{r.to_s}" return 0 if exp =~ /infinity/i || exp =~ /[a-z]/i #puts "evaling #{exp}" #puts "eval, L #{l.class} #{l.inspect} #{str} R #{r.inspect}" raise exp if exp =~ /[a-z]/i res = eval(exp) #puts "evaled #{exp} to #{res}" res end |
#left_associative? ⇒ Boolean
8 9 10 |
# File 'lib/extract/math_calc.rb', line 8 def left_associative? true end |
#operator? ⇒ Boolean
11 12 13 |
# File 'lib/extract/math_calc.rb', line 11 def operator? %w(+ - / * ^).include?(str) end |
#precedence ⇒ Object
14 15 16 17 |
# File 'lib/extract/math_calc.rb', line 14 def precedence h = {"*" => 10, "/" => 10, "+" => 5, "-" => 5, "^" => 15} h[str] end |
#to_s ⇒ Object
39 40 41 |
# File 'lib/extract/math_calc.rb', line 39 def to_s str end |