How to pluralize a character in Ruby (on Rails)?

This works, but it looks a bit ugly:

s = :shop s.to_s.pluralize.to_sym # => :shops 

Is there a better way to pluralize Symbol ?

+6
ruby ruby-on-rails pluralize
source share
3 answers

You can pluralize String , which is the actual text. Symbol are more abstract.

So, by definition, no. However, perhaps you can open the definition of the Symbol class and add:

 class Symbol def pluralize to_s.pluralize.to_sym end end 

Then you can simply call:

 :shop.pluralize # => :shops 
+8
source share

No, that’s it.

+4
source share

If you are comfortable with changing Ruby classes, then this works:

 class Symbol def pluralize self.to_s.pluralize.to_sym end end 

I have yet to find a more elegant solution, although I suspect that if that were the case, it would most likely be Rails implementing something similar to what I had above.

+3
source share

All Articles