Module: StringMagic::Utilities::Inflection

Included in:
String, StringMagic
Defined in:
lib/string_magic/utilities/inflection.rb

Instance Method Summary collapse

Instance Method Details

#humanizeObject


Human-readable




56
57
58
59
60
61
62
63
# File 'lib/string_magic/utilities/inflection.rb', line 56

def humanize
  return '' if empty?
  gsub('_', ' ')
    .gsub(/([a-z])([A-Z])/, '\1 \2')
    .downcase
    .strip
    .capitalize
end

#ordinalizeObject


Ordinalisation


‘1’.ordinalize #=> ‘1st’



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/string_magic/utilities/inflection.rb', line 40

def ordinalize
  return self unless /\A-?\d+\z/.match?(self)

  num = to_i
  suffix = if (11..13).cover?(num % 100)
             'th'
           else
             { 1 => 'st', 2 => 'nd', 3 => 'rd' }.fetch(num % 10, 'th')
           end
  self + suffix
end

#to_pluralObject


Plural ↔ singular




10
11
12
13
14
15
16
17
18
19
# File 'lib/string_magic/utilities/inflection.rb', line 10

def to_plural
  return '' if empty?

  case downcase
  when /(s|sh|ch|x|z)\z/                 then self + 'es'
  when /[^aeiou]y\z/i                    then chop + 'ies'
  when /(f|fe)\z/                        then sub(/(f|fe)\z/, 'ves')
  else                                       self + 's'
  end
end

#to_singularObject



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/string_magic/utilities/inflection.rb', line 21

def to_singular
  return '' if empty?

  down = downcase
  if    down.end_with?('ies')           then sub(/ies\z/i, 'y')
  elsif down.end_with?('ves') && length > 3
    sub(/ves\z/i, down[-4] == 'i' ? 'fe' : 'f') # knives → knife, leaves → leaf
  elsif down =~ /(ses|shes|ches|xes|zes)\z/i    then sub(/es\z/i, '')
  elsif down.end_with?('s') && length > 1       then chop
  else                                           self
  end
end