Intro to Ruby

Class 3

Homework Discussion

How was last week's homework? Do you have any questions or concepts that you'd like to discuss?

Review

  • Conditions - if, elsif, else
  • Loops - while, for

What we will cover today

  • Collections
  • Methods
  • Objects

Collections

There are three main types:

  • Ranges
  • Arrays
  • Hashes

new_range = (1..10)

new_array = [1, 3, 5]

new_hash = {"dog" => "snoopy", "bird" => "woodstock"}
          

Ranges


inclusive_range = (1..3)  # contains 1, 2, 3
exclusive_range = (1...3) # contains 1, 2
letter_range = ('a'..'e') # contains 'a', 'b', 'c', 'd', 'e'
          

Ranges are simply the range of values between the given first and last elements.

Inclusive ranges have two dots, and include the last element. Exclusive ranges have three dots, and do not include the last element.

Ranges need to be defined from lowest value to highest.

Ranges

Try out these range methods in IRB.


(1..99).max
('b'...'z').include?('j')
(890..902).begin
(890..902).first(4)
(890..902).last(3)
(890..902).end
(28..22).min

('a'...'g').each do |l|
puts "#{l} is a pretty good letter"
end

(22..28).to_a
          

Learn more about ranges here.

Arrays

Arrays have square brackets and can be filled with any type of object: integers, floats, strings, even other arrays or hashes.


new_array = [1, 3, 5, 89, 212, 7, -100]
arr = ["wow", "woooo", "zowie"]
array = Array.new #will have no elements inside it initially
varied_array = ["one", 2, "THREE", 0.4, ["five", 6]]

# methods to get information about an array
new_array.length
new_array.count
arr.include?("yee ha")
          

Arrays are a great way to keep track of information that changes frequently.

Accessing Elements in an Arrays

Arrays are ordered and are integer-indexed, starting at 0.

Elements can be accessed by their position.


new_array = [1, 3, "wow", 5, "cool", 212, 7, -100]

new_array[0]          # returns the zeroth element
new_array[2]          # returns the third element
new_array[-1]         # returns the last (1st from the end) element
new_array.last        # returns the last element
new_array.first       # returns the first element
          

Adding & Deleting From Arrays

Adding and removing items to an array can be done in a variety of ways. These are the most common.


new_array = ["wow", "woooo", "zowie"]

#add
new_array.push("hot diggity") # adds argument as last element
new_array << "yikes"          # adds argument as last element

#remove
new_array.delete("wow")       # deletes the element that matches argument
new_array.pop                 # removes and returns the last element
          

More Array Methods

Arrays are used a lot in Ruby. There are a lot of cool methods available for them.


arr = ["dog", "cat", "turtle", "parakeet", "ferret"]

arr.index("dog")  # returns the index of the element that matches argument
arr.join          # returns a string made up of all the elements
arr.clear         # removes all elements from the array
arr.reverse       # returns new array with same elements, reversed
arr.shuffle       # returns new array with same elements, shuffled
arr.uniq          # returns a new array with only unique elements
arr.size          # returns the number of elements in the array
arr.empty?        # returns a boolean
          

Learn more about arrays here.

Hashes

Hashes have curly braces and hash rockets and can be filled with any data type: integers, floats, strings, even arrays and hashes.


grades_hash = { "Jane Doe" => 10, "Jim Doe" => 6, "Jan Doe" => 8}

# methods to find information about hashes
grades_hash.length
grades_hash.count
grades_hash.size
grades_hash.has_key?("Jan Doe")
grades_hash.has_value?(10)

          

Syntax:

{ key => value, key => value }

Accessing Elements in Hashes

Hashes are unordered. Hashes are like dictionaries, with unique key / value pairs.

Because hashes can have any type of object as an idex, and are unordered, we must access values by their key.


grades_hash = { "Jane Doe" => 10, "Jim Doe" => 6, "Jan Doe" => 8}

grades_hash["Jane Doe"]   # returns 10, the value of this key
grades_hash["Jim Doe"]   # returns 6, the value of this key
grades_hash.first         # returns first key/value pair... probably
          

Adding & Removing from Hashes


new_hash = { 1 => "a", "d" => 12, "f" => 35 }

# add
new_hash["z"] = 43   # adds a new key/value pair "z" => 43

#remove
new_hash.delete("d") # removes key/value pair with specified key
new_hash.clear       # removes all key/value pairs
          

More Hash methods


chapters = {"My Early Home" => (1..15), "The Hunt" => (16..28),
        "My Breaking In" => (29..46), "Birtwick Park" => (46..60)}

chapters.count      # returns number of key/value pairs in hash
chapters.keys       # returns an array of all the keys in hash
chapters.has_key?("How It Ended")  # returns a boolean
chapters.invert     # returns new hash with old one's values
                    # and keys swapped!
            

Learn more about hashes here.

Enumerable

Arrays and Hashes are both members of the Enumerable class. There are a lot of cool methods available for Enumerable, including each.

.each with Ranges

This is the simplest!


(3..8).each do |n|
  puts n * 4
end
          

.each with Arrays

Can be simple or more complex, depending on the array.


pets_array = ["dog", "cat", "turtle", "parakeet", "ferret"]

pets_array.each do |p|
  puts "I like #{p}s!!"
end
          

.each with Hashes

Each element has a key and value that needs to be dealt with.


grades_hash = { "Jane Doe" => 10, "Jim Doe" => 6, "Jan Doe" => 8}

grades_hash.each do |key, value|
puts "#{key}'s grade is #{value}"
end
          

Let's Develop It


Enumerable

Visit this page and copy the contents of the Gist to a local file. Save it as pets.rb. We'll work with it together.

Enumerable- pets.rb

Two ways to use this file:

  1. Load it into IRB: load 'pets.rb'
  2. Just type your methods into the bottom of the pets.rb file, and then run the file to see the output (NOT in IRB): ruby 'pets.rb'

Enumerable: Collect and Map

Returns an array with the results of running the block on each element. Can be used interchangably.


$pets.collect{|p| p[:name]}      # returns array of all pet names
$pets.map{|p| p[:talents]}       # returns array of all pets' talents
          

Enumerable: Reject and Select

Returns an array with all elements that did or did not meet the critera in code block.


$pets.reject{|p| p[:talents].include?("napping") }
  # returns array of pets whose talents do not include napping
$pets.select{|p| p[:breed] == "Slug"}
  #returns array of all pets that have a breed of Slug
          

Let's Develop It

How many pets do we have total?

What is the name of the first pet?

Print the name of each pet (hint: use a .each loop)

How many of our pets are nocturnal?

What are the names of all the pets with four legs?