Skip to content

Instantly share code, notes, and snippets.

@nosolopau
Created May 28, 2012 11:20
Show Gist options
  • Save nosolopau/2818621 to your computer and use it in GitHub Desktop.
Save nosolopau/2818621 to your computer and use it in GitHub Desktop.
Singularize method for Rails String class
# encoding: UTF-8
class String
def singularize_es
if self[-2..-1].index(/es/) # Ending in 'es'
if self[-4..-1].index(/[^aeiou][^aeiou]es/) # Ending in consonant + consonant + 'es': remove 's' ('coche' > 'coches')
self[0..-2]
else
if self[-3..-1].index(/[^aeiou]es/) # Ending in consonant + 'es'
case self[-3..-1]
when 'nes' # Ending in 'nes': add accent to precedent vowel ('camiones' > 'camión')
replacements = {'a' => 'á', 'e' => 'é', 'i' => 'í', 'o' => 'ó', 'u' => 'ú'}
self[-4..-4] = replacements[self[-4..-4]]
self[0..-3]
when 'ces' # Ending in 'ces': replace with 'z' ('peces' > 'pez')
self[0..-4] + 'z'
else # General case: remove 'es' ('pieles' > 'piel')
self[0..-3]
end
else # Ending in vowel + 'es': remove 's' ('pies' > 'pie')
self[0..-2]
end
end
else
if self[-2..-1].index(/s/) # Ending in 's'
self[0..-2]
else
self
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment