In Ruby, I want to store some stuff in a Hash, but I don't want it to be case-sensitive. So for example:
h = Hash.new
h["HELLO"] = 7
puts h["hello"]
This should output 7, even though the case is different. Can I just override the equality method of the hash or something similar?
Thanks.
While Ryan McGeary's approach works great and is almost certainly the correct way to do it, there is a bug that I haven't been able to discern the cause of, which breaks the
Hash[]
method.For example:
Although I've not been able to find or fix the underlying cause of the bug, the following hack does ameliorate the problem:
In general, I would say that this is a bad plan; however, if I were you, I'd create a subclass of hash that overrides the
[]
method:To prevent this change from completely breaking independent parts of your program (such as other ruby gems you are using), make a separate class for your insensitive hash.
After overriding the assignment and retrieval functions, it's pretty much cake. Creating a full replacement for Hash would require being more meticulous about handling the aliases and other functions (for example, #has_key? and #store) needed for a complete implementation. The pattern above can easily be extended to all these related methods.
Any reason for not just using string#upcase?
If you insist on modifying hash, you can do something like the following
Since it was brought up, you can also do this to make setting case insensitive:
I also recommend doing this using module_eval.
If you really want to ignore case in both directions and handle all Hash methods like
#has_key?
,#fetch
,#values_at
,#delete
, etc. , you'll need to do a little work if you want to build this from scratch, but if you create a new class that extends from class ActiveSupport::HashWithIndifferentAccess, you should be able to do it pretty easily like so:Here's some example behavior: