class RPNCalculator::Input::Parser
Attributes
allowed_operators[R]
Public Class Methods
new(allowed_operators)
click to toggle source
# File lib/rpn-calculator/input/parser.rb, line 4 def initialize(allowed_operators) @allowed_operators = allowed_operators end
Public Instance Methods
parse(input_string)
click to toggle source
# File lib/rpn-calculator/input/parser.rb, line 8 def parse(input_string) parsed_input = input_without_whitespace( join_consecutive_numbers(input_string.split('')) ) invalid_elements = parsed_input_errors(parsed_input) Result::Parser.new(parsed_input, invalid_elements) end
Private Instance Methods
any_operator?(elements)
click to toggle source
# File lib/rpn-calculator/input/parser.rb, line 42 def any_operator?(elements) elements.any? { |e| !number_or_period?(e) } end
input_without_whitespace(split_string)
click to toggle source
# File lib/rpn-calculator/input/parser.rb, line 20 def input_without_whitespace(split_string) split_string.reject { |e| e == ' ' } end
join_consecutive_numbers(split_string)
click to toggle source
# File lib/rpn-calculator/input/parser.rb, line 31 def join_consecutive_numbers(split_string) split_string.each_with_index.inject([]) do |result, (element, index)| if index.zero? || any_operator?([split_string[index - 1], element]) result << element else result[-1] += element end result end end
number?(number_string)
click to toggle source
# File lib/rpn-calculator/input/parser.rb, line 50 def number?(number_string) true if Float(number_string) rescue ArgumentError false end
number_or_period?(number_string)
click to toggle source
# File lib/rpn-calculator/input/parser.rb, line 46 def number_or_period?(number_string) number_string == '.' || number?(number_string) end
parsed_input_errors(parsed_input)
click to toggle source
# File lib/rpn-calculator/input/parser.rb, line 24 def parsed_input_errors(parsed_input) parsed_input.inject([]) do |result, element| result << element unless allowed_operators.include?(element) || number?(element) result end end