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.
casecmp is a String class method in Ruby which is Case-insensitive version of String#<=>. For now, case-insensitivity only works on characters A-Z/a-z, not all of the Unicode characters. This method is different from casecmp! method.
In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.
Iterating over a HashYou can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.
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.
class HashClod < Hash def [](key) super _insensitive(key) end def []=(key, value) super _insensitive(key), value end # Keeping it DRY. protected def _insensitive(key) key.respond_to?(:upcase) ? key.upcase : key end end you_insensitive = HashClod.new you_insensitive['clod'] = 1 puts you_insensitive['cLoD'] # => 1 you_insensitive['CLod'] = 5 puts you_insensitive['clod'] # => 5
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With