I frequently check if a specific value is in a large array. I can do this by Array#index. To make this more efficient, I created a hash of the array values and called Hash#has_key?:
Method 1
arr = ["a","b","c","d"] arr.index("c")Method 2
h = {"a"=> true, "b"=> true, "c"=> true, "d"=> true} h.has_key?("c")
But I noticed ruby throws an exception if a key isn't in a given hash. I'm wondering what the relative performance of the two methods is.
h.fetch)h["a"]would not throw an exception in your example code; it would simply returnnil