Class: Keisan::StringAndGroupParser

Inherits:
Object
  • Object
show all
Defined in:
lib/keisan/string_and_group_parser.rb

Defined Under Namespace

Classes: GroupPortion, OtherPortion, Portion, StringPortion

Constant Summary collapse

STRING_CHARACTER_REGEX =
/["']/
OPEN_GROUP_REGEX =
/[\(\{\[]/
CLOSED_GROUP_REGEX =
/[\)\}\]]/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expression, start_index: 0, ending_character: nil) ⇒ StringAndGroupParser

Ending character is used as a second ending condition besides expression size



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/keisan/string_and_group_parser.rb', line 160

def initialize(expression, start_index: 0, ending_character: nil)
  index = start_index
  @portions = []

  while index < expression.size && (ending_character.nil? || expression[index] != ending_character)
    case expression[index]
    when STRING_CHARACTER_REGEX
      portion = StringPortion.new(expression, index)
      index = portion.end_index
      @portions << portion

    when OPEN_GROUP_REGEX
      portion = GroupPortion.new(expression, index)
      index += portion.size
      @portions << portion

    when CLOSED_GROUP_REGEX
      raise Keisan::Exceptions::TokenizingError.new("Tokenizing error, unexpected closing brace #{expression[start_index]}")

    else
      portion = OtherPortion.new(expression, index)
      index += portion.size
      @portions << portion
    end
  end

  @size = index - start_index
end

Instance Attribute Details

#portionsObject (readonly)

An ordered array of “portions”, which



153
154
155
# File 'lib/keisan/string_and_group_parser.rb', line 153

def portions
  @portions
end

#sizeObject (readonly)

An ordered array of “portions”, which



153
154
155
# File 'lib/keisan/string_and_group_parser.rb', line 153

def size
  @size
end

Instance Method Details

#to_sObject



189
190
191
# File 'lib/keisan/string_and_group_parser.rb', line 189

def to_s
  portions.map(&:to_s).join
end