Hashes Implementation in Ruby

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. The major difference between arrays in hashes is in the custom set up of hash indexes. Indexes in arrays are numeric and indexes in hashes can be of any object type you decide to use.

Ruby specifies two ways of creating hashes.

  1.        my_hash = {:one=>1, :two=>2} or alternatively my_hash = {one=>1, two=>2}
  2.        my_hash = Hash[:one,1, :two:2]

Accessing hashes follows similar to array access pattern of passing an index to a hash in square brackets.

my_hash[:one] //returns 1
my_hash[:three] = 3 //adds new hash element to 3 with index of three

Hashes can be interrogated for other types of information such as list of indexes, values or conversion of hash into an array.

my_hash.key
my_hash.values
my_hash.to_a

It is important to note that hashes contain references to object and not objects themselves. Hashes are used in storing key-value pairs and array can always be used in case key-value par is not required. Both, arrays and hashes can be traversed for the information at about the same efficiency rate. Once again, the main difference between hashes and arrays are in the type of key: either number or objects.

It is interesting to note that hashes in Ruby are actually implemented as arrays.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…