Class: RPN::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/rpn/parser.rb

Defined Under Namespace

Classes: InvalidDelimiterError, MalformedStringError

Constant Summary collapse

TOKENS =
%w{. + - * / ^}
ALIASES =
{'^' => '**'}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(delimiter) ⇒ Parser

Returns a new instance of Parser.



11
12
13
# File 'lib/rpn/parser.rb', line 11

def initialize delimiter
  @delimiter = validate(delimiter)
end

Instance Attribute Details

#delimiterObject (readonly)

Returns the value of attribute delimiter.



9
10
11
# File 'lib/rpn/parser.rb', line 9

def delimiter
  @delimiter
end

Instance Method Details

#parse(string) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/rpn/parser.rb', line 15

def parse string
  string.gsub(/#{delimiter}+/, delimiter)\
        .split(delimiter).map(&:strip).map do |element|
    if element.to_i.zero? && element != '0'
      if TOKENS.include?(element)
        (ALIASES[element] || element).to_sym
      else
        raise MalformedStringError.new("Offending token: #{element}")
      end
    else
      element =~ /\./ ? element.to_f\
                      : element.to_i
    end
  end
end