Class: Naturally::Segment

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/naturally/segment.rb

Overview

An entity which can be compared to other like elements for sorting. It’s an object representing a value which implements the Comparable interface.

Instance Method Summary collapse

Constructor Details

#initialize(v) ⇒ Segment

Returns a new instance of Segment.



8
9
10
# File 'lib/naturally/segment.rb', line 8

def initialize(v)
  @val = v
end

Instance Method Details

#<=>(other) ⇒ Object



12
13
14
# File 'lib/naturally/segment.rb', line 12

def <=>(other)
  to_array <=> other.to_array
end

#to_arrayObject



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/naturally/segment.rb', line 16

def to_array
  if @val =~ /^(\p{Digit}+)(\p{Alpha}+)$/
    [$1.to_i, $2]
  elsif @val =~ /^(\p{Alpha}+)(\p{Digit}+)$/
    [$1, $2.to_i]
  elsif @val =~ /^\p{Digit}+$/
    [@val.to_i]
  else
    [@val]
  end
end