Class: Tefil::Calculator

Inherits:
TextFilterBase show all
Defined in:
lib/tefil/calculator.rb

Instance Method Summary collapse

Methods inherited from TextFilterBase

#filter

Constructor Details

#initialize(options = {}) ⇒ Calculator

Returns a new instance of Calculator.



8
9
10
11
12
13
# File 'lib/tefil/calculator.rb', line 8

def initialize(options = {})
  @options = options
  @preserve = options[:preserve]
  @ruby = options[:ruby]
  super(options)
end

Instance Method Details

#process_stream(in_io, out_io) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/tefil/calculator.rb', line 15

def process_stream(in_io, out_io)
  in_io.each do |line|
    eq = line.chomp

    eq.gsub!(/\{/, '(' )
    eq.gsub!(/\}/, ')' )
    eq.gsub!(/\\times/, '*' )

    if @ruby
      eq.gsub!(/\^/, '**' )
      eq.gsub!(/sqrt/, 'Math::sqrt' )
      eq.gsub!(/log\(/, 'Math::log(' )
      eq.gsub!(/l\(/, 'Math::log(' )
      eq.gsub!(/exp\(/, 'Math::exp(' )
      eq.gsub!(/e\(/, 'Math::exp(' )
      result = eval(eq)
    else
      eq.gsub!(/\(/, '\(' )
      eq.gsub!(/\)/, '\)' )
      eq.gsub!(/\*/, '\*' )

      result = `echo  #{eq} | bc -l`.chomp
      result.sub!(/^\./, '0.')
      result.sub!(/^-\./, '-0.')
      result.sub!(/^0$/, '0.0')
    end

    out_io.print line.chomp + " = " if @preserve
    out_io.puts result
  end
end