Skip to content

Instantly share code, notes, and snippets.

@stacietaylorcima
Last active January 10, 2018 02:24
Show Gist options
  • Save stacietaylorcima/37786a2f28478c7bc451de12840742cc to your computer and use it in GitHub Desktop.
Save stacietaylorcima/37786a2f28478c7bc451de12840742cc to your computer and use it in GitHub Desktop.
Use Array objects to store/retrieve information.

Ruby: Arrays

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.

Creating Arrays in Ruby

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"

Accessing Array Elements

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"

Insertion

  • 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.
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

Removal

  • 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
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

Sorting

  • 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.
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"]

%w Syntax

  • 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"]

Negative Indexes

  • 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"

Ranges

  • 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"]
@stacietaylorcima
Copy link
Author

stacietaylorcima commented Jan 9, 2018

Exercises - Array Definition

  • Create a method named new_array. It should use four arguments and return an Array with those same arguments. Start by defining the method structure:
def new_array(a,b,c,d)
  array = [a, b, c, d]
end

  • Create another method named first_and_last. It should use one argument, an Array, and return a new Array with only the first and last objects of the argument:
def first_and_last(a)
  [a.first, a.last]
end

@stacietaylorcima
Copy link
Author

stacietaylorcima commented Jan 9, 2018

Array's slice Method in Ruby

Let'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 nil

  • Returns the element at index

Example:

  • We have 10 students.
  • We want to tell the students to form 2 groups.
  • I want to select a team captain, so I choose a random number in my head and find who is at that index in the list.
  • That lucky duck will be a team captain!
class_list = ["Miles", "Jenny", "Mila", "Joan", "Sam", "Alice", "Peter", "Ralph", "Stacie", "Todd"]

class_list.slice(4) 
# => "Sam"
  • Sam is a team captain! Go, Sam.
  • In this case, you can access an object at a specific index by coding name_of_array.slice(index)
  • Ruby will return the object at that index.

slice(start, length) → new_ary or nil

  • returns a subarray starting at the start index and continuing for length elements

Example:

  • We have 10 students. We want to put the students into 2 groups.
  • I want to slice the list in half to get my groups. I know I'll need 2 groups of 5.
class_list = ["Miles", "Jenny", "Mila", "Joan", "Sam", "Alice", "Peter", "Ralph", "Stacie", "Todd"]

group_1 = class_list.slice(0, 5) 
p group_1
#=> ["Miles", "Jenny", "Mila", "Joan", "Sam"]

group_2 = class_list.slice(5, 5) 
p group_2
#=> ["Alice", "Peter", "Ralph", "Stacie", "Todd"]
  • In this example, I can split the lists by using slice(index_where_i'd_like_the_split_to_start, length_of_the_new_array)
  • Since the array index starts at 0, in group_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 nil

  • returns a subarray specified by range of indices

Example:

  • I don't know how many students we have, but I know I can only handle 7 and I'm going to send the rest with the teacher's aid.
  • To see my list of students, I can use the slice range option.
class_list = ["Miles", "Jenny", "Mila", "Joan", "Sam", "Alice", "Peter", "Ralph", "Stacie", "Todd"]

my_group = class_list.slice(0..6) 
p my_group
#=> ["Miles", "Jenny", "Mila", "Joan", "Sam", "Alice", "Peter"]
  • Since the index starts at 0, and I want to pull 7 students, I'll pass the range (0..6).
  • This will return the list of students I am taking!

Special cases

  • Negative indices count backward from the end of the array (-1 is the last element). For start and range cases the starting index is just before an element.
    • In the example below, I want to get a list of the last 4 students on the list.
    • Since I want to count backward in the array, I'll pass the arguments (-4..-1).
class_list = ["Miles", "Jenny", "Mila", "Joan", "Sam", "Alice", "Peter", "Ralph", "Stacie", "Todd"]

class_list.slice(-4..-1) 
#=> ["Peter", "Ralph", "Stacie", "Todd"]

  • Returns nil if the index (or starting index) are out of range.
    • In the example below, I am trying to access the range 11-16, but since there is no object at index 11, it will return nil.
class_list = ["Miles", "Jenny", "Mila", "Joan", "Sam", "Alice", "Peter", "Ralph", "Stacie", "Todd"]

my_group = class_list.slice(11..16) 
p my_group
#=> nil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment