Test if a word is singular or plural in Ruby on Rails Test if a word is singular or plural in Ruby on Rails ruby-on-rails ruby-on-rails

Test if a word is singular or plural in Ruby on Rails


Well in rails, you can do a string#singularize|#pluralize comparison to return a true or false value.

But I would think due to the nature of language itself, this might need some backup to do be completely accurate.

You could do something like this

def test_singularity(str)  str.pluralize != str && str.singularize == strend

But to see how accurate, I ran a quick set of words.

%w(word words rail rails dress dresses).each do |v|  puts "#{v} : #{test_singularity(v)}"endword : truewords : falserail : truerails : falsedress : falsedresses : false

I was a little surprised actually, since 'dress' does get pluralized properly, but when it goes through the #singularize it runs into a bit of a snag.

'dress'.pluralize # => dresses'dress'.singularize # => dres


Most of the times i never test for singularity or plural, i just convert it to the singular or plural form i require.

In Rails 2.3.x this was possible, writing something like this

plural_form = org_word.singularize.pluralizesingular_form = org_word.pluralize.singularize

Working further on this, a working function is easy to supply:

require 'active_support'def is_singular?(str)  str.pluralize.singularize == strend%w(word words rail rails dress dresses).each do |v|  puts "#{v} : #{is_singular?(v)}"end

which gives the following output:

word : truewords : falserail : truerails : falsedress : truedresses : false

In Rails 4, with the given words, it is now much easier. You can just do

plural_form = org_word.pluralizesingular_form = org_word.singularize

and thus the function becomes much easier as well:

require 'active_support'def is_singular?(str)  str.singularize == strend


Neither ruby nor rails come with a specific method for testing for "plurality" on words.

As nowk said, the most you can do is implement them yourself, comparing with word.pluralize and word.singularize. This will give you a quick-and-cheap-and-generally-good way of testing. It will fail some times, though.

If you need more precision, you will need to use the Ruby Linguistics gem, which can deal with dress and dresses properly (but it's heavier).