So I have a question of best practice in terms of extending functionality of common Ruby datatypes.
So Rails of course has a great method pluralize which takes a string and pluralizes it. What I’m particularly interested in is that you can call
"square".pluralize
and receive
=> "squares"
in return. What I want to do is a similar sort of thing — except for a Hash. For the sake of this question, let’s say I have a method pluralize_each which pluralizes each key and value of a hash.
def pluralize_each hash
hash.each {|key,value| puts key.pluralize + "=>" + value.pluralize }
end
How can I manipulate this method so that I can call it on just a hash?
For example, I want to be able to call
{"cat" => "dog"}.pluralize_each
#=> {"cats" => "dogs"}
(Let’s forget that this particular method isn’t fully functional right now, with nested hashes and such.)
Is there any way to do this except for extending the Hash class? I would think that there would be a way.
With a module:
EDIT: WHY?
@KL-7 legitimately asked a class edit vs module extension. This is my opinion:
If you are writing something organic, modules can be useful in order to optimize refactoring / code organization. Example:
This module permits you to define a clean way to define pluralizations for various classes; you could add a configuration, separate the pluralization methods in various files, etc.
Anyway, if you just want to add a
pluralizemethod to Hash class, there is no problem editing the Hash class (just ensure you are not overriding another method, with amethod_defined?check f.e.)