How to pluralize a symbol in Ruby (on Rails)?
-
09-10-2019 - |
Question
This works, but looks a little bit ugly:
s = :shop
s.to_s.pluralize.to_sym # => :shops
Is there a nicer way to pluralize a Symbol
?
Solution
You can pluralize a String
, which represents actual text. Symbol
s are a bit more abstract.
So, by definition, no. However, perhaps you could open up the Symbol class definition and add:
class Symbol
def pluralize
to_s.pluralize.to_sym
end
end
Then, you can just call:
:shop.pluralize # => :shops
OTHER TIPS
Nope, that's the way.
If you're comfortable altering Ruby's 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 if there was, it would probably just be Rails implementing something similar to what I have above.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow