alternatives to Hash#index that works without warning in both Ruby 1.8 and 1.9
Question
I've got some ruby code that I'm converting to Ruby 1.9. One warning I get is Hash#index is deprecated; use Hash#key
But Hash#key is not defined in Ruby 1.8, so I can't use that directly. Does anybody have a good alternative?
I've got a couple of options (which I'll post as answers so you can vote), but I'm hoping for better.
Solution
You could also invert the hash:
{ :hello => :world }.invert[:world] # ==> :hello
No monkey-patching or external dependencies, but probably less efficient for most purposes.
OTHER TIPS
Another choice is to monkeypatch:
class Hash
alias_method(:key, :index) unless method_defined?(:key)
end
require 'backports/1.9.1/hash/key'
{:hello => :world}.key(:world) # ==> :hello on all ruby versions
My backports gem defines all of Ruby 1.8.7 and many Ruby 1.9 / 2.0 methods. This makes it much easier to have code that works on all of these platforms.
One possibility is:
(hash.respond_to?(:key) ? hash.key(t) : hash.index(t))
But that's gross and adds overhead.
It's rather ugly, but works too:
h = { :a => 1 }
[:key,:index].find{|method| break h.send(method, 1) if h.respond_to?(method) }