Class: Naturally::Segment
- Inherits:
-
Object
- Object
- Naturally::Segment
- 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 which can convert itself to an array.
Instance Method Summary collapse
- #<=>(other) ⇒ Object
-
#initialize(v) ⇒ Segment
constructor
A new instance of Segment.
-
#to_array ⇒ Array
A representation of myself in array form which enables me to be compared against another instance for sorting.
Constructor Details
#initialize(v) ⇒ Segment
Returns a new instance of Segment.
9 10 11 |
# File 'lib/naturally/segment.rb', line 9 def initialize(v) @val = v end |
Instance Method Details
#<=>(other) ⇒ Object
13 14 15 |
# File 'lib/naturally/segment.rb', line 13 def <=>(other) to_array <=> other.to_array end |
#to_array ⇒ Array
Returns a representation of myself in array form which enables me to be compared against another instance for sorting. The array is prepended with a symbol so two arrays are always comparable.
31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/naturally/segment.rb', line 31 def to_array # TODO: Refactor, probably via polymorphism if @val =~ /^(\p{Digit}+)(\p{Alpha}+)$/ [:int, $1.to_i, $2] elsif @val =~ /^(\p{Alpha}+)(\p{Digit}+)$/ [:str, $1, $2.to_i] elsif @val =~ /^\p{Digit}+$/ [:int, @val.to_i] else [:str, @val] end end |