Array and Hashes in Ruby

Array in Ruby:

x = [1, 2, 3, 4]

It is a basic array, it has four elements. Each element is an integer and is separated by commas from its neighbouring elements. Square brackets are used to denote an array literal.

Elements can be accessed by their index. To access a particular element, an array is followed by the index contained within square brackets. This is called an element reference.


x = [1, 2, 3, 4]
puts x[2]


Hashes in Ruby:

Arrays are collections of objects that are called Hash. However, hashes have a different storage format and way to define each object within the collection. Rather than having an assigned position in a list, objects within a hash are given a key that points to them. It’s more like a dictionary than a list, as there’s no guaranteed order, but just simple links between keys and values. Here’s a basic hash with two entries:

dictionary = { 'cat' => 'feline animal', 'dog' => 'canine animal' }