Class: Keisan::StringAndGroupParser::GroupPortion

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

Constant Summary collapse

OPENING_TO_CLOSING_BRACE =
{
  "(" => ")",
  "{" => "}",
  "[" => "]",
}

Instance Attribute Summary collapse

Attributes inherited from Portion

#end_index, #start_index

Instance Method Summary collapse

Constructor Details

#initialize(expression, start_index) ⇒ GroupPortion

Returns a new instance of GroupPortion.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/keisan/string_and_group_parser.rb', line 97

def initialize(expression, start_index)
  super(start_index)

  case expression[start_index]
  when OPEN_GROUP_REGEX
    @opening_brace = expression[start_index]
  else
    raise Keisan::Exceptions::TokenizingError.new("Internal error, GroupPortion did not start with brace")
  end

  @closing_brace = OPENING_TO_CLOSING_BRACE[opening_brace]

  parser = StringAndGroupParser.new(expression, start_index: start_index + 1, ending_character: closing_brace)
  @portions = parser.portions
  @size = parser.size + 2

  if start_index + size > expression.size || expression[start_index + size - 1] != closing_brace
    raise Keisan::Exceptions::TokenizingError.new("Tokenizing error, group with opening brace #{opening_brace} did not have closing brace")
  end
end

Instance Attribute Details

#closing_braceObject (readonly)

Returns the value of attribute closing_brace.



89
90
91
# File 'lib/keisan/string_and_group_parser.rb', line 89

def closing_brace
  @closing_brace
end

#opening_braceObject (readonly)

Returns the value of attribute opening_brace.



89
90
91
# File 'lib/keisan/string_and_group_parser.rb', line 89

def opening_brace
  @opening_brace
end

#portionsObject (readonly)

Returns the value of attribute portions.



89
90
91
# File 'lib/keisan/string_and_group_parser.rb', line 89

def portions
  @portions
end

#sizeObject (readonly)

Returns the value of attribute size.



89
90
91
# File 'lib/keisan/string_and_group_parser.rb', line 89

def size
  @size
end

Instance Method Details

#to_sObject



118
119
120
# File 'lib/keisan/string_and_group_parser.rb', line 118

def to_s
  opening_brace + portions.map(&:to_s).join + closing_brace
end