Ruby – Why Use an Array or Hash as a Hash Key?

ruby

i'm using Ruby 1.9.3

I figured out that you can use an array, or a hash as hash key in ruby:

h = Hash.new

h[Array.new] = "Why?"
h[Array.new] # Output: "Why?"

h[Hash.new] = "It doesn't make sense"
h[Hash.new] # Output: "It doesn't make sense"

But an object works differently…

h[Object.new] = "LOL"
h[Object.new] # Output: "nil"

But this one works as expected:

o = Object.new

h[o] = "LMAO"
h[o] # Output: "LMAO"

Tried this:

o = Object.new           # Output: #<Object:0x2c78c10>
h["#<Object:0x2c78c10>"] # Output: nil

Tried it in Python and PHP and it throws an error.

I'm just curious about how it works, and why would you want to use an array, or a hash as hash key in ruby?

Thanks.

Best Answer

Why wouldn't you? You can use any object as a Hash key in Ruby. (Well, any object that responds to hash and eql?, but since there are definitions of those in Object, that's pretty much all objects.) It would be strange and inconsistent if you would arbitrarily exclude two classes from that.

Related Topic