Arrays

An array stores multiple values of the same data type. Array is similar to range, but the only difference is that range must represent continuous sequences. Array on the other hand contains collection of data; it doesn't need to be consecutive sequence. The real life examples of arrays are:

  • Egg cartons containing eggs
  • Chess board with its pieces etc

Example of Array

Representation of Array

The numbers 0 to 7 are called Array Index. They are used to access the array elements.


Defining an Array

We define an array by putting square brackets around data. For example,

numbers = [1,3,5,7,9]

Here numbers is a collection of 5 numbers(data) of type integers.

Array Example in Ruby

The element of an array is accessed by using array name followed by index. For example, the first element of numbers array is accessed by numbers[0]

Accessing Array Elements in Ruby

To sum up all the elements of the grades array, following statement is used.

Sum = grades[0] + grades[1] + grades[2] + grades[3]

Sum of ELements of Array in Ruby

However, there are more efficient ways of accessing all the elements of an array. We look at those, when we get to our Lesson about Loops. As of now, to access the array elements you specify its index. Sometimes it is called offset.


Turning Sequence into an Array

The sequences(Range) can be converted into array using to_a method.

Turning Range into Array in Ruby


Hash

Hash is another data structure to store the collection of data. It is often called as associative structure, because we store data in key-value pairs. A classic example of associative structure is Dictionary, where the word is the key and the definition of the word is the value. In hash, to find the value we have to look at the key.

Below is an example demonstrating how to define a hash in ruby :

pincode = {
		'Abc' = '123',
		'xyz' = '980',
		'def' = '456',
	}	

Hash in Ruby

Representation of Hash in Ruby


Representation of Hash

We retrieve the value from the hash by presenting the key to the hash name like an array subscript.

To retrieve the number of Praveen : numbers['Praveen']

If we try to retrieve a value using a key that doesn’t exist, it returns nil.

Accessing Hash elements in Ruby example


This way you can ensure that whether the key exists or not. If it returns nil it represents that the key doesn't exist.