Class: Naturally::NumberElement

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

Overview

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(v) ⇒ NumberElement

Returns a new instance of NumberElement.



35
36
37
# File 'lib/naturally.rb', line 35

def initialize(v)
  @val = v
end

Instance Attribute Details

#valObject

Returns the value of attribute val.



33
34
35
# File 'lib/naturally.rb', line 33

def val
  @val
end

Instance Method Details

#<=>(other) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/naturally.rb', line 39

def <=>(other)
  if both_are_integers_without_letters(other)
    return @val.to_i <=> other.val.to_i
  end

  if either_is_numbers_followed_by_letters(other)
    return simple_normalize(@val) <=> simple_normalize(other.val)
  end

  if either_is_letters_followed_by_numbers(other)
    return reverse_simple_normalize(@val) <=> reverse_simple_normalize(other.val)
  end

  return @val <=> other.val
end

#both_are_integers_without_letters(other) ⇒ Object



63
64
65
# File 'lib/naturally.rb', line 63

def both_are_integers_without_letters(other)
  pure_integer? && other.pure_integer?
end

#either_is_letters_followed_by_numbers(other) ⇒ Object



55
56
57
# File 'lib/naturally.rb', line 55

def either_is_letters_followed_by_numbers(other)
  letters_with_numbers? || other.letters_with_numbers?
end

#either_is_numbers_followed_by_letters(other) ⇒ Object



59
60
61
# File 'lib/naturally.rb', line 59

def either_is_numbers_followed_by_letters(other)
  numbers_with_letters? || other.numbers_with_letters?
end

#letters_with_numbers?Boolean

Returns:

  • (Boolean)


75
76
77
# File 'lib/naturally.rb', line 75

def letters_with_numbers?
  val =~ /^[a-zA-Z]+\d+$/
end

#numbers_with_letters?Boolean

Returns:

  • (Boolean)


71
72
73
# File 'lib/naturally.rb', line 71

def numbers_with_letters?
  val =~ /^\d+[a-zA-Z]+$/
end

#pure_integer?Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/naturally.rb', line 67

def pure_integer?
  @val =~ /^\d+$/
end

#reverse_simple_normalize(n) ⇒ Object



87
88
89
90
91
92
93
# File 'lib/naturally.rb', line 87

def reverse_simple_normalize(n)
  if n =~ /^([a-zA-Z]+)(\d+)$/
    return [$1, $2.to_i]
  else
    return [n.to_s]
  end
end

#simple_normalize(n) ⇒ Object



79
80
81
82
83
84
85
# File 'lib/naturally.rb', line 79

def simple_normalize(n)
  if n =~ /^(\d+)([a-zA-Z]+)$/
    return [$1.to_i, $2]
  else 
    return [n.to_i]
  end
end