Alan Coromano
Alan Coromano

Reputation: 26038

Available types for Ruby's hash key

Must a key be a string or int, or might it be of any object type?

Upvotes: 3

Views: 2216

Answers (2)

Thomas
Thomas

Reputation: 181960

Not documented?

[Hash] is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.

(Emphasis mine.)

Upvotes: 5

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230411

A very-very common type is Symbol, which you didn't mention. But it can be any object, really.

class Foo; end

f1, f2 = Foo.new, Foo.new

h = {
  f1 => 3,
  f2 => 4
}

h # => {#<Foo:0x007fed4b04bb00>=>3, #<Foo:0x007fed4b04bad8>=>4}
h[f1] # => 3
h[f2] # => 4

Upvotes: 7

Related Questions