Created
June 6, 2016 17:44
-
-
Save esquinas/f9a58be5beedcf88e71e85c96e567424 to your computer and use it in GitHub Desktop.
Quick and dirty pluralization in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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