Class: Calc::Parser

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

Overview

Parses delimited input according to 3 rules (in order):

  • Coerces valid numeric input into BigDecimal

  • Includes input that is on its whitelist

  • Ignores all other input

Instance Method Summary collapse

Constructor Details

#initialize(whitelist:) ⇒ Parser

Returns a new instance of Parser.

Parameters:

  • whitelist (Array<String>)

    characters to include in parsed output


23
24
25
# File 'lib/calc/parser.rb', line 23

def initialize(whitelist:)
  @whitelist = Set[*whitelist]
end

Instance Method Details

#prepare(input:, delimeter: ' ') ⇒ Array<BigDecimal>, ...

Parameters:

  • input (String)

    single item or space-delimited items

  • delimeter (String) (defaults to: ' ')

    character to use the boundary between items in the input

Returns:

  • (Array<BigDecimal>)

    if input was numeric

  • (Array)

    if input was not in the parser's whitelist

  • (Array<BigDecimal,String>)

    if input contained numeric and whitelisted items


35
36
37
38
39
40
41
42
43
# File 'lib/calc/parser.rb', line 35

def prepare(input:, delimeter: ' ')
  input.split(delimeter).each_with_object([]) do |item, output|
    if item.match?(NUMERIC)
      output << item.to_d
    elsif whitelist.include?(item)
      output << item
    end
  end
end