Module: Sevgi::Function::Pluralize

Included in:
Sevgi::Function
Defined in:
lib/sevgi/function/string.rb

Overview

Lightweight English pluralization helper.

Constant Summary collapse

UNCOUNTABLES =

Words that should not be pluralized.

Hash[
*%w[
  sheep
  fish
  sheep
  series
  species
  money
  rice
  information
  equipment
].map { [it, true] }.flatten
      ]
.freeze
IRREGULARS =

Singular-to-plural forms that do not follow suffix rules.

Hash[
*%w[
  child
  children
  datum
  data
  man
  men
  move
  moves
  person
  people
  sex
  sexes
  woman
  women
  zombie
  zombies
]
      ]
.freeze
PLURALS =

Plural forms already accepted as plural.

IRREGULARS.invert.freeze
RULES =

Ordered suffix replacement rules.

[
  [/(quiz)$/i, "\\1zes"],
  [/^(oxen)$/i, "\\1"],
  [/^(ox)$/i, "\\1en"],
  [/^(m|l)ice$/i, "\\1ice"],
  [/^(m|l)ouse$/i, "\\1ice"],
  [/(matr|vert|ind)(?:ix|ex)$/i, "\\1ices"],
  [/(x|ch|ss|sh)$/i, "\\1es"],
  [/([^aeiouy]|qu)y$/i, "\\1ies"],
  [/(hive)$/i, "\\1s"],
  [/(?:([^f])fe|([lr])f)$/i, "\\1\\2ves"],
  [/sis$/i, "ses"],
  [/([ti])a$/i, "\\1a"],
  [/([ti])um$/i, "\\1a"],
  [/(buffal|tomat)o$/i, "\\1oes"],
  [/(bu)s$/i, "\\1ses"],
  [/(alias|status)$/i, "\\1es"],
  [/(octop|vir)i$/i, "\\1i"],
  [/(octop|vir)us$/i, "\\1i"],
  [/^(ax|test)is$/i, "\\1es"],
  [/s$/i, "s"],
  [/$/, "s"]
].freeze

Instance Method Summary collapse

Instance Method Details

#pluralize(word) ⇒ String

Pluralizes an English word using a small built-in rule set.

Examples:

F.pluralize("post")         # => "posts"
F.pluralize("octopus")      # => "octopi"
F.pluralize("sheep")        # => "sheep"
F.pluralize("CamelOctopus") # => "CamelOctopi"

Parameters:

  • word (Object)

    word to pluralize

Returns:



99
100
101
102
103
104
105
106
107
# File 'lib/sevgi/function/string.rb', line 99

def pluralize(word)
  result = word.to_s.dup

  return result if word.empty? || UNCOUNTABLES.key?(result) || PLURALS.key?(result)
  return IRREGULARS[result] if IRREGULARS.key?(result)

  RULES.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
  result
end