Alex Rivera | Logout

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

Asked 2010-01-08T19:59:07.387
23

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.

Edit
Report

1 Answer

2

Any reason for not just using string#upcase?

h = Hash.new

h["HELLO"] = 7

puts h["hello".upcase]

If you insist on modifying hash, you can do something like the following

class Hash
alias :oldIndexer :[]

def [](val)
   if val.respond_to? :upcase then oldIndexer(val.upcase) else oldIndexer(val) end
end
end

Since it was brought up, you can also do this to make setting case insensitive:

class Hash
alias :oldSetter :[]=
def []=(key, value)
    if key.respond_to? :upcase then oldSetter(key.upcase, value) else oldSetter(key, value) end
end
end

I also recommend doing this using module_eval.

answered 2010-01-08T20:03:45.050

Your Answer