Ruby: Arrays and Hashes
June 4, 2015
Arrays and hashes are common data types used to store information. Both store collections of object.
Arrays
An array in Ruby is an object. Array can store object of different data type. Each element in array can be refferd to by an index. Ruby like in others languages a first elemen has index 0. There are to type creating arrays. Arrays can be instantiated with the new method:
a = Array.new() //create an ampty array []
a.push(2) => a[2]
a.push(45) => a[2,45] //push method add an item to the end of the array.
b = Array.new(3) => [nil, nil, nil]
c = Array.new(3, "99") => ["99","99","99"] //create array with 3 elemntsv
Another way to create array just put elements in square brackets:
a = [1,2,3]
a = [] // create empty array
If you want to get elemenf from array you can access it by index
a[0] => 1
a[3] => nil //because arry doesn't have any elemnt by index 3. Remember index start from 0!
Also, if you want take last element and don't think about index you can use method 'last'
a.last => 3
The same way for the first element
a.first => 1
But if you want to get index of this element you can use method 'index'. But remember this method return index of first occurs element in array or nil if there is not an element in array.
a.index(1) => 1
a.index(45) => nil
Nested Arrays
Nested array is an array with one or more arrays nested inside of it. Nested arrays are useful when storing things in multiple categories. There can be multiple levels of nesting.
a = [[1, 2, 4], ["a", "b", "c"]]
If we want to access the first value in nested array, we would do so in the same way as a regular array:
a[0] => [1, 2, 4]
a[1] => ["a", "b", "c"]
If you want to dip into the inner arrays, you should add an exstra index:
a[0][0] => 1
a[1][1] => "b"
This is simple examle how to crate and work with arrays in Ruby. More information you can find here
Hashes
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type.
Hashes enumerate their values in the order that the corresponding keys were inserted.
A Hash can be easily created by using its implicit form:
name = { "Julia" => 23, "Max" => 34 }
Also you can use sumbols for key:
name = { :Julia => 23, :Max => 34 }
In similar way to array empty hash can be created by using empty curly brackets
name = {}
Or a new hash can also be created by using the new method on the class
name = Hash.new
For getting value in array we used index but when we work with hash we use key:
fruits = {:orange => 34, :apple => 12, :banana => 48}
fruits[:orange] => 34
To modify value :
fruits[:orange] = 9
fruits => fruits = {:orange => 9, :apple => 12, :banana => 48
More infomations about hashes you can find here