Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of integers as hash keys

Tags:

hashmap

ruby

Is it appropriate to use integers as keys in a Ruby hash?

Every example from documentation shows a string or symbol being used as a key, but never an integer.

Internally, would integers somehow get converted to strings? I have seen some conflicting information on the subject.

In other words, is there any significant disadvantage to using integer keys to a hash?

like image 719
timpone Avatar asked Oct 08 '11 01:10

timpone


People also ask

Can hash key be integer?

An explanation, why there are no examples with integers as Hash-keys. Hash-keys have (most of the times) a meaning. It may be an attribute name and its value (e.g. :color => 'red' ...). When you have an integer as a key, your semantic may be 'first, second ...' (1).

How do you hash integers?

The most commonly used method for hashing integers is called modular hashing: we choose the array size M to be prime, and, for any positive integer key k, compute the remainder when dividing k by M. This function is very easy to compute (k % M, in Java), and is effective in dispersing the keys evenly between 0 and M-1.

What are integer keys?

An integer key just means you assign a value to an integer (i.e. your name is just an integer).

What is the purpose of the hash key?

The key helps identify the data and operates as an input to the hashing function, while the hash code or the integer is then mapped to a fixed size. Hash tables support functions that include the following: insert (key, value) get (key)


1 Answers

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 => 1 uno = 1 => 1 one.object_id => 3 one.object_id == uno.object_id => true 
like image 187
dylankb Avatar answered Sep 27 '22 19:09

dylankb