Class: Keisan::StringAndGroupParser

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

Defined Under Namespace

Classes: CommentPortion, GroupPortion, OtherPortion, Portion, StringPortion

Constant Summary collapse

COMMENT_CHARACTER_REGEX =
/[#]/
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



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/keisan/string_and_group_parser.rb', line 197

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]}")

    when COMMENT_CHARACTER_REGEX
      portion = CommentPortion.new(expression, index)
      index += portion.size
      @portions << portion

    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



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

def portions
  @portions
end

#sizeObject (readonly)

An ordered array of “portions”, which



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

def size
  @size
end

Instance Method Details

#to_sObject



231
232
233
# File 'lib/keisan/string_and_group_parser.rb', line 231

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