ruby 54 lines · 8 steps

Building an English pluralizer in Ruby

A layered lookup of irregulars, uncountables, and regex rules turns any singular noun into its plural form.

Explained by highlit
1class Pluralizer
2 IRREGULARS = {
3 "person" => "people",
4 "child" => "children",
5 "foot" => "feet",
6 "tooth" => "teeth",
7 "mouse" => "mice",
8 "goose" => "geese",
9 "man" => "men",
10 "woman" => "women"
11 }.freeze
12 
13 UNCOUNTABLE = %w[fish sheep series species deer equipment information].freeze
14 
15 RULES = [
16 [/(matr|vert|ind)(?:ix|ex)$/i, '\1ices'],
17 [/(x|ch|ss|sh)$/i, '\1es'],
18 [/([^aeiouy]|qu)y$/i, '\1ies'],
19 [/(?:([^f])fe|([lr])f)$/i, '\1\2ves'],
20 [/sis$/i, 'ses'],
21 [/(bu)s$/i, '\1ses'],
22 [/([ti])um$/i, '\1a'],
23 [/s$/i, 's'],
24 [/$/, 's']
25 ].freeze
26 
27 def self.pluralize(count, word)
28 "#{count} #{count.abs == 1 ? word : plural(word)}"
29 end
30 
31 def self.plural(word)
32 return word if UNCOUNTABLE.include?(word.downcase)
33 
34 if (irregular = IRREGULARS[word.downcase])
35 return match_case(word, irregular)
36 end
37 
38 RULES.each do |pattern, replacement|
39 return word.sub(pattern, replacement) if word =~ pattern
40 end
41 
42 word
43 end
44 
45 def self.match_case(original, replacement)
46 if original == original.upcase
47 replacement.upcase
48 elsif original == original.capitalize
49 replacement.capitalize
50 else
51 replacement
52 end
53 end
54end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Ordering rules from most specific to a catch-all lets a single pass handle both exceptions and the common case.
  2. 2Separating irregular words and uncountables into constant tables keeps the regex logic clean and readable.
  3. 3Preserving the original word's casing after transformation makes a helper reusable across any capitalization.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building an English pluralizer in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code