Class: RKelly::CharPos

Inherits:
Object
  • Object
show all
Defined in:
lib/rkelly/char_pos.rb

Overview

Represents a character position in source code.

It’s a value object - it can’t be modified.

Constant Summary collapse

EMPTY =

A re-usable empty position

CharPos.new(1,0,-1)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(line, char, index) ⇒ CharPos

Returns a new instance of CharPos.



10
11
12
13
14
# File 'lib/rkelly/char_pos.rb', line 10

def initialize(line, char, index)
  @line = line
  @char = char
  @index = index
end

Instance Attribute Details

#charObject (readonly)

Returns the value of attribute char.



8
9
10
# File 'lib/rkelly/char_pos.rb', line 8

def char
  @char
end

#indexObject (readonly)

Returns the value of attribute index.



8
9
10
# File 'lib/rkelly/char_pos.rb', line 8

def index
  @index
end

#lineObject (readonly)

Returns the value of attribute line.



8
9
10
# File 'lib/rkelly/char_pos.rb', line 8

def line
  @line
end

Instance Method Details

#next(string) ⇒ Object

Creates a new character position that’s a given string away from this one.



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/rkelly/char_pos.rb', line 18

def next(string)
  if !string
    CharPos.new(@line, @char, @index)
  elsif string.include?("\n")
    lines = string.split("\n", -1)
    CharPos.new(@line + lines.length - 1, lines.last.length, @index + string.length)
  else
    length = string.length
    CharPos.new(@line, @char + length, @index + length)
  end
end

#to_sObject Also known as: inspect



30
31
32
# File 'lib/rkelly/char_pos.rb', line 30

def to_s
  "{line:#{@line} char:#{@char} (#{@index})}"
end