Concept | Description |
---|---|
Array | An object that represents a collection of objects |
Access | To access an element at a particular index, pass the index inside square brackets like array_name[0]. Use negative numbers to retrieve elements from the right to the left starting at -1 |
Insertion | To add an element to an existing Array object using methods like push, <<, unshift, insert |
Removal | To remove elements from an Array object using methods like pop, shift, clear, delete |
Sorting | We can sort a collection by calling the sort method on an Array object |
Ranges | Use ranges to return numbers between start and end like (start..end) |
Objectives
- Define the Array data type in Ruby.
- Demonstrate how to access elements in an Array.
- Demonstrate how to modify elements in an Array.
- Demonstrate how to use Range.
favorite_colors = ["Blue", "Red"] # initializing and storing in variable
[1,2,3] #initializing and returning without storing
top_languages = Array.new #initializes an empty array
favorite_food = Array.new(5, "pizza") #initializes array with 5 elements, each storing "pizza"
Index:
- To retrieve an element, use the same syntax that specifies a character in a string
[]
. - Like string indexes, the index count for an array starts at
0
.
fruits = ["apple", "banana", "orange"]
fruits[0]
#=> "apple"
fruits[2]
#=> "orange"
**Simple Array Methods:
- Return first or last element in array:
fruits = ["apple", "banana", "orange"]
fruits.last
#=> "orange"
fruits.first
#=> "apple"
- Find the array's length:
fruits.length
#=> 3
- Join Elements in an Array:
- If we call it with no arguments, it will squish the elements together.
- If you pass an argument to it, it will be used as a separator between the elements.
fruits = ["apple", "banana", "orange"]
p fruits.join #=> "applebananaorange"
p fruits.join(', ') #=> "apple, banana, orange"
push
or<<
- The
push
method (or<<
shovel operator when passing only one object) will **add any comma seperated arguments passed to it to the end of the array in the order they are passed.
- The
grocery_list = ["milk"]
grocery_list.push("corn flakes", "coffee")
grocery_list << "creamer"
p grocery_list # ["milk", "corn flakes", "coffee", "creamer"]
upshift
- Add an element to the beginning of the array.
grocery_list.unshift('mug')
p grocery_list # ["mug", "milk", "corn flakes", "coffee", "creamer"]
insert
- Insert an element into a specific position in the array.
- The first argument is the index at which we need the insertion to take place
- The second argument will be the object or objects we are going to insert.
grocery_list.insert(1, "stirrer")
p grocery_list # ["mug", "stirrer", "milk", "corn flakes", "coffee", "creamer"]
include?
- Insert an object conditionally based on whether or not it's already in the array.
- The
include?
method uses an argument and it returns as true if the item is found in the collection, or it returns as false if it's not found. - We use the
include?
method in a conditional expression to determine whether to add the item to the list or not.
if grocery_list.include?("milk") #we already have milk in the list
"Milk is already on the list."
else # milk wasn't on the list, let's add it
grocery_list.push("milk")
end
pop
- Remove an element from the end of an array.
- The ‘pop’ method will remove the last element from the Array, and it will also return it in case we want to store it.
theater_queue = ["Bob", "Marcy", "Michael"]
next_customer = theater_queue.pop
p next_customer # returns "Michael"
p theater_queue # returns ["Bob", "Marcy"]
shift
- Remove element from start of an array and return it.
theater_queue = ["Bob", "Marcy"]
next_customer = theater_queue.shift
p next_customer # returns "Bob"
p theater_queue # returns ["Marcy"]
clear
- Empty contents of an array.
theater_queue.clear
p theater_queue.empty? # returns true
delete
- The
delete
method takes an argument to look for in the array and deletes/returns it if found. - If the argument is not found, it will return
nil
- The
suitcase = ["toothbrush", "toothpaste", "shoes", "shirts", "pants", "bathing suit"]
storming = true
if storming #it's storming where we're headed, leave the bathing suit home
suitcase.delete("bathing suit")
end
p suitcase # returns ["toothbrush", "toothpaste", "shoes", "shirts", "pants"]
delete_at
- Takes an integer as an argument and deletes/returns any element at that index.
numbers = [1,2,3,3,4]
numbers.delete_at(2) # deletes and returns the element at index of 2
sort
method to rearrange the order of elements in the array.- If
sort
is called with no arguments, it will arrange the elemenets in ascending order. - If there are strings it will sort them based on their ASCII code.
- This method returns a new array! The array that the
sort
method is called on remains unchanged.
- If
names = ["Chrono", "Marle", "Robo", "Magus", "agnes", "bill", "charlie"]
names.sort # returns ["Chrono", "Magus", "Marle", "Robo", "agnes", "bill", "charlie"]
- Mutator Versions of Mehtods:
- The mutator version of a method will alter the object it's called on.
- This means that the colelction will be sorted in place and no new array will be created.
- These methods will end with the bang operator - !. Programmer-defined methods will use ! in the method definition.
names = ["Chrono", "Marle", "Robo", "Magus", "agnes", "bill", "charlie"]
names.sort! # returns ["Chrono", "Magus", "Marle", "Robo", "agnes", "bill", "charlie"]
p names # returns ["Chrono", "Magus", "Marle", "Robo", "agnes", "bill", "charlie"]
- Percent Strings, like
%w
, are followed with opening and closing symbols (usually {}, but others like [] or !! will work). - The Strings inside the Percent Strings are delimited with a space:
fruits = %w{apple banana orange}
# => ["apple", "banana", "orange"]
- This syntax only creates Strings, not numbers or other types, inside the Array.
integers = [1, 2, 3]
#=> [1, 2, 3]
strings = ["1", "2", "3"]
#=> ["1", "2", "3"]
integers_or_strings = %w{1 2 3}
#=> ["1", "2", "3"]
- Capitolization Matters!
- When capitalized, %W processes interpolation:
%w{10 20 #{10+20}}
#=> ["10", "20", "\#{10+20}"]
%W{10 20 #{10+20}}
#=> ["10", "20", "30"]
- Indexes, like 0 and 1, retrieve elements from an Array going from the left to the right.
- Ruby also supports negative indexes, that retrieve elements from the right to the left.
- When using negative indexes, counting starts at -1, rather than 0.
fruits = ["apple", "banana", "orange"]
fruits[-1]
#=> "orange"
fruits[-2]
#=> "banana"
fruits[-3]
#=> "apple"
- A Range specifies a sequential set of Strings or Integers.
(1..5)
("a".."e")
- We can also index multiple Array elements with a Range.
fictional_cats = ['Cheshire Cat', 'Garfield', 'Catwoman', 'The Cat in the Hat']
fictional_cats[1..3]
#=> ["Garfield", "Catwoman", "The Cat in the Hat"]
- We can also use negative indexes in Ranges.
fictional_cats = ['Cheshire Cat', 'Garfield', 'Catwoman', 'The Cat in the Hat']
fictional_cats[-2..-1]
#=> ["Catwoman", "The Cat in the Hat"]
Exercises - Grocery List
In this exercise we'll create a program that allows you to manage a grocery list. You'll need to create three methods for this program, each of which is detailed below.
add_item
add_item
method should take two arguments. The first argument is the item you want to add to the list and the second argument is the array (i.e. list) that the item will be added to. Don't add an item to the list if it already exists in the list. For example, you could start with this:remove_item
full_list