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"]
Array's
slice
Method in RubyLet's take a look at how to use the
slice
method in ruby. We'll pretend we're elementary school teachers and we're splitting up the class for a field trip!slice(index)
→ obj or nilExample:
name_of_array.slice(index)
slice(start, length)
→ new_ary or nilExample:
slice(index_where_i'd_like_the_split_to_start, length_of_the_new_array)
0
, ingroup_1
I will use the argument(0)
for my starting point and(5)
for the length because this is how many objects I want in my new array.slice(range)
→ new_ary or nilExample:
0
, and I want to pull 7 students, I'll pass the range(0..6)
.Special cases
(-4..-1)
.nil
if the index (or starting index) are out of range.11-16
, but since there is no object at index11
, it will returnnil
.