Class: NaturalSort::SegmentedString

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/natural_sort/segmented_string.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ SegmentedString

Returns a new instance of SegmentedString.



10
11
12
# File 'lib/natural_sort/segmented_string.rb', line 10

def initialize(input)
  @input = input.to_s
end

Instance Attribute Details

#inputObject (readonly)

Returns the value of attribute input.



8
9
10
# File 'lib/natural_sort/segmented_string.rb', line 8

def input
  @input
end

Instance Method Details

#<=>(other) ⇒ Object

Raises:

  • (ArgumentError)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/natural_sort/segmented_string.rb', line 18

def <=>(other)
  raise ArgumentError unless SegmentedString === other

  other_segments = other.segments

  segments.each_with_index do |segment, index|
    other_segment = other_segments[index]
    return 1 if other_segment.nil?
    result = compare_segments(segment, other_segment)
    return result unless result.zero?
  end

  other_segments.length > segments.length ? -1 : 0
end

#segmentsObject



14
15
16
# File 'lib/natural_sort/segmented_string.rb', line 14

def segments
  @segments ||= tokens.map { |token| Segment.new(token) }
end