tags:

views:

100

answers:

4

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.

A: 

One possibility is:

(hash.respond_to?(:key) ? hash.key(t) : hash.index(t))

But that's gross and adds overhead.

Bryan Larsen
+3  A: 

Another choice is to monkeypatch:

class Hash
  alias_method(:key, :index) unless method_defined?(:key)
end
Bryan Larsen
A: 

It's rather ugly, but works too:

h = { :a => 1 }
[:key,:index].find{|method| break h.send(method, 1) if h.respond_to?(method) }
MBO
+1  A: 
require 'backports'
{:hello => :world}.key(:world)  # ==> :hello on all ruby versions

My backports gem defines all of Ruby 1.8.7 and many Ruby 1.9 methods. This makes it much easier to have code that works on all of these platforms.

Marc-André Lafortune
you meant `{:hello => :world}.key(:world)`, I hope? Relying on a commonly-used library to monkey patch is probably better than monkey-patching randomly in each library. OTOH, nobody appreciates added depdendencies.
Bryan Larsen
Oups, yes, indeed. I fixed that, thanks.My goal is to avoid everyone the trouble of figuring out how to monkey-patch stuff correctly; I (usually) run my implementations against rubyspecs too...
Marc-André Lafortune
I'm going to accept your answer. I actually went with the monkey patch myself, but I had other considerations not listed in the question. This is probably the right answer for most others.
Bryan Larsen