Bryan Larsen
Bryan Larsen

Reputation: 10006

alternatives to Hash#index that works without warning in both Ruby 1.8 and 1.9

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.

Upvotes: 2

Views: 2116

Answers (5)

Marc-André Lafortune
Marc-André Lafortune

Reputation: 79562

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.

Upvotes: 1

Derek Bruneau
Derek Bruneau

Reputation: 76

You could also invert the hash:

{ :hello => :world }.invert[:world]    # ==> :hello

No monkey-patching or external dependencies, but probably less efficient for most purposes.

Upvotes: 4

Bryan Larsen
Bryan Larsen

Reputation: 10006

Another choice is to monkeypatch:

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

Upvotes: 6

MBO
MBO

Reputation: 30995

It's rather ugly, but works too:

h = { :a => 1 }
[:key,:index].find{|method| break h.send(method, 1) if h.respond_to?(method) }

Upvotes: 0

Bryan Larsen
Bryan Larsen

Reputation: 10006

One possibility is:

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

But that's gross and adds overhead.

Upvotes: 0

Related Questions