Data Structures: Objects and Arrays
So far, we know data types like boolean
, numbers
and strings
. In this chapter, we are going to look into more complex data structures.
Arrays
Sometimes, we want to work with a collection of data and values. For example, we might have a list of odd numbers between 0 and 10 – 1, 3, 5, 7 and 9.
How should we store this list as a whole? We could use string "1 3 5 7 9"
, but if I want to interact with the numbers, I have to convert from string back to numbers. Yikes.
In programming, there's a data type called array, designed for storing a list of values of the same kind. An array of "1, 3, 5, 7, 9" is written as [1, 3, 5, 7, 9]
. An array is defined with the open and close brackets [
and ]
. Each item in the array is separated by a comma ,
.
How about [1, 3, "hello", 7, 9]
? Would this work? Not all items are of the same kind (numbers in this case). The answer is yes. This can work, but it's not preferred. An array should contain items of the same kind (i.e. all items should be number or string).
In arrays, we count things starting from 0, not 1. For example, the first item of [1, 3, 5, 7, 9]
is 1
. And, we say that it is at index 0.
[<index 0>, <index 1>, <index 2>, ...]
So the number 9
is at index 4.
Manipulating arrays
How do you add / append an item to the end of an array? Use .push
.
arr = [1,2]
arr.push(3)
arr
=> [1,2,3]
So, this is to append to the back of the array. What if you want to append to the front of the array? Use .unshift
.
arr = [1,2,3]
arr.unshift(4)
arr
=> [4, 1, 2, 3]
To remove the last item in the array, you can use .pop
.
arr = [1,2,3]
arr.pop
arr
=> [1, 2]
To remove the first item in the array, you can use .shift
.
arr = [1,2,3]
arr.shift
arr
=> [2, 3]
To remove an item at a certain index, you can pass a parameter to .delete_at
.
# to remove the item at the fifth index (index 5)
arr = ['a','b','c','d','e','f','g','h','i']
arr.delete_at(5) # 5 is the index of the item you want to remove
arr
=> ['a','b','c','d','e','g','h','i']
To see or get a value at a certain index, you can use the square brackets []
arr = ['a','b','c','d']
arr[2] # index 2
=> 'c'
To change a value at a certain index, you assign new value by doing
arr = ['a','b','c','d']
arr[2] = 'Z' # index 2
arr
=> ['a','b','Z','d']
You can get the number of items using .length
.
You don't have to memorize all these methods. It acts as a documentation for you to refer back to when you need them. It's like a dictionary for English words.
Since an array is a list of items of similar kinds, sometimes, you want to loop through an array. To do that, you can use the .each
method.
For example,
arr = [1, 2, 3, 4, 5, 6]
arr.each do |item|
puts item # print out the value of item
end
Here, .each
will iterate through each item one by one. During each iteration, the value of the item will be stored inside the variable item
. We can access this variable for processing if we want. In this case, we used it to print out the value.
Hashes
We said that an array is a list of items of the same kind. Well, a hash
is like the opposite. A hash helps store arbitrary collections of properties. For example, we can create a hash that represents properties of a person.
{
name: 'Bill Gates',
net_worth: '82.9 billion USD',
education: 'Harvard College',
age: 61,
occupation: ['Business Leader', 'Entrepreneur', 'Philanthropist']
}
A hash is defined by an opening and closing curly bracket {
and }
. Inside the {}
, you can have multiple properties expressed in key-value pairs.
For example, the key name
is followed by the value Bill Gates
; together, the key and value act as a pair. In this case, we have five key-value
pairs. Each pair is separated by a comma ,
.
To access a property, you just have to specify the key to get the value.
person = {
name: 'Bill Gates',
net_worth: '82.9 billion USD',
education: 'Harvard College',
age: 61,
occupation: ['Business Leader', 'Entrepreneur', 'Philanthropist']
}
person[:age]
=> 61
When we define a hash key-value pair like this
name: 'Bill Gates'
, the key is a symbol. Therefore when we access it, we need to use the symbol:name
Similarly, to modify the value of a property, you can specify the key and assign the value of your choice.
person = {
name: 'Bill Gates',
net_worth: '82.9 billion USD',
education: 'Harvard College',
age: 61,
occupation: ['Business Leader', 'Entrepreneur', 'Philanthropist']
}
person[:age] = 62
person[:age]
=> 62
To get all the keys of a hash, you can use .keys
method. To get all the values, you can use the .values
method.
person = {
name: 'Bill Gates',
net_worth: '82.9 billion USD',
education: 'Harvard College',
age: 61,
occupation: ['Business Leader', 'Entrepreneur', 'Philanthropist']
}
person.keys
=> [:name, :net_worth, :education, :age, :occupation]
person.values
=> ["Bill Gates", "82.9 billion USD", "Harvard College", 61, ["Business Leader", "Entrepreneur", "Philanthropist"]]
You can also delete a key-value pair in a hash, simply use the delete
method and pass the key as the argument. The delete
method will return the value of the key if the key exists or return nil
if it doesn't.
dog = {
name: 'Billy',
age: '3'
}
dog.delete(:age)
=> '3'
dog
=> { name: 'Billy' }