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

doctororange picture doctororange · Nov 26, 2009 · Viewed 15.2k times · Source

Quick question.

How can I test a word to see if it is singular or plural?

I'd really like:

test_singularity('word') # => true
test_singularity('words') # => false

I bet rails is capable!

Thanks.

Answer

nowk picture nowk · Nov 26, 2009

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 == str
end

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)}"
end

word : true
words : false
rail : true
rails : false
dress : false
dresses : 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