Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a hash in Ruby that compares strings, ignoring case?

Tags:

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.

like image 700
Colen Avatar asked Jan 08 '10 19:01

Colen


People also ask

How do you make a string case insensitive in Ruby?

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.

How do you instantiate a Hash in Ruby?

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.

Can you iterate through a Hash Ruby?

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.


1 Answers

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.

like image 79
Myrddin Emrys Avatar answered Sep 22 '22 13:09

Myrddin Emrys