Skip to content

Instantly share code, notes, and snippets.

@esquinas
Created June 6, 2016 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esquinas/f9a58be5beedcf88e71e85c96e567424 to your computer and use it in GitHub Desktop.
Save esquinas/f9a58be5beedcf88e71e85c96e567424 to your computer and use it in GitHub Desktop.
Quick and dirty pluralization in Ruby
# CAUTION, it opens String class
String.class_eval do
# HACK: quick and dirty english pluralization.
def to_plural(*arg)
plural = lambda do |str|
if str =~ /\s\z|men\z|people\z|[^aious]s\z/i # is a plural already
str
elsif str =~ /\Aman\z|woman\z/i # man & woman, except caiman, human...
str.sub(/an\z/i, 'en')
elsif str =~ /[^aeiou][aeiou]?(f|fe)\z/ # knife, half...
str.sub(Regexp.new("#{Regexp.last_match(1)}\\z"), 'ves')
elsif str =~ /[^o]y\z/ # berry, activity... except boy, joy, convoy...
str.chop!
str.concat 'ies'
elsif str =~ /[sxz]\z|[cs]h\z/ # box, fish, pitch...
str.concat 'es'
else
str.concat 's'
end
end
if arg[0].nil? || arg[0] != 1
plural.call self
else
self
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment