Usage of integers as hash keys
Others looking at the answers here might find it interesting to know that an exception happens when you use integers as symbol keys in a Ruby hash {symbol: value}
hash = {1: 'one'} # will not work hash = {1 => 'one'} # will work
Requested Explanation:
The simplest answer for why the first example fails is probably that to_sym
is not a method that's been implemented for Fixnum integers.
To go more in depth to maybe explaining why that is, one of the main benefits to using symbols is that two symbols are in fact "the same object". Or at least they share the same object ids.
:foo.object_id == :foo.object_id=> true
Strings that are the same do not share the same objects, and therefore do not share the same object ids.
"foo".object_id == "foo".object_id=> false
Like symbols, Fixnum integers that are the same will have the same object ids. Therefore you don't really need to convert them into symbols.
one = 1=> 1uno = 1=> 1one.object_id=> 3one.object_id == uno.object_id=> true
of course you can use integers as keys...
h = {1 => 'one', 2 => 'two', 3 => 'three'}(1..3).each do |i| puts h[i]end
=>
onetwothere
irb is your friend! try it..
In fact you can use any Ruby object as the key (or the value).We usually don't think about using Hashes like this, but it could be quite useful.
Edit:As Óscar López points out, the object just has to respond to .hash
for it to work as a key in a Ruby Hash.