Exercises

Hint: you can refer to the Ruby doc for Array and Hash for help.

Exercises

To ask LSBot exercise-specific questions, click the "Work in Code Editor" button next to each exercise solution.
Exercise 1

Use the each method of Array to iterate over [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], and print out each value.

View Our Solution Work in Code Editor

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# one line version
arr.each { |number| puts number }

# multi-line version
arr.each do |number|
  puts number
end

Video Walkthrough

Duration: 1:50

Exercise 2

Same as above, but only print out values greater than 5.

View Our Solution Work in Code Editor

# one line version
arr.each { |number| puts number if number > 5 }

# multi-line version
arr.each do |number|
  if number > 5
    puts number
  end
end

Video Walkthrough

Duration: 1:52

Exercise 3

Now, using the same array from #2, use the select method to extract all odd numbers into a new array.

View Our Solution Work in Code Editor

# one line version
new_array = arr.select { |number| number % 2 != 0 }

# multi-line version
new_array = arr.select do |number|
  number % 2 != 0
end

Video Walkthrough

Duration: 3:05

Exercise 4

Append 11 to the end of the original array. Prepend 0 to the beginning.

View Our Solution Work in Code Editor

# Append
arr.push(11)
# --- or ---
arr << 11

# Prepend
arr.unshift(0)

Video Walkthrough

Duration: 2:12

Exercise 5

Get rid of 11. And append a 3.

View Our Solution Work in Code Editor

# Remove from end of array
arr.pop

# Append
arr << 3
# --- or ---
arr.push(3)

Video Walkthrough

Duration: 2:11

Exercise 6

Get rid of duplicates without specifically removing any one value.

View Our Solution Work in Code Editor

# Does not modify calling object
arr.uniq

# Modifies the calling object
arr.uniq!

Video Walkthrough

Duration: 2:15

Exercise 7

What's the major difference between an Array and a Hash?

View Our Solution Work in Code Editor

The major difference between an array and a hash is that a hash contains a key value pair for referencing by key.

Video Walkthrough

Duration: 1:20

Exercise 8

Create a Hash, with one key-value pair, using both Ruby syntax styles.

View Our Solution Work in Code Editor

hash = {:name => 'bob'} # <= old version
hash = {name: 'bob'} # <= new version

Video Walkthrough

Duration: 1:27

Exercise 9

Suppose you have a hash h = {a:1, b:2, c:3, d:4}

1. Get the value of key `:b`.

2. Add to this hash the key:value pair `{e:5}`

3. Remove all key:value pairs whose value is less than 3.5

View Our Solution Work in Code Editor

1. h[:b]

2. h[:e] = 5

3.

  # one line version
  h.delete_if { |k, v| v < 3.5 }

  # multi-line version
  h.delete_if do |k, v|
    v < 3.5
  end

Video Walkthrough

Duration: 3:24

Exercise 10

Can hash values be arrays? Can you have an array of hashes? (give examples)

View Our Solution Work in Code Editor

Yes

# hash values as arrays
hash = {names: ['bob', 'joe', 'susan']}

# array of hashes
arr = [{name: 'bob'}, {name: 'joe'}, {name: 'susan'}]

Video Walkthrough

Duration: 1:28

Exercise 11

Given the following data structures, write a program that copies the information from the array into the empty hash that applies to the correct person.

contact_data = [["joe@email.com", "123 Main st.", "555-123-4567"],
            ["sally@email.com", "404 Not Found Dr.", "123-234-3454"]]

contacts = {"Joe Smith" => {}, "Sally Johnson" => {}}

# Expected output:
#  {
#    "Joe Smith"=>{:email=>"joe@email.com", :address=>"123 Main st.", :phone=>"555-123-4567"},
#    "Sally Johnson"=>{:email=>"sally@email.com", :address=>"404 Not Found Dr.",  :phone=>"123-234-3454"}
#  }

View Our Solution Work in Code Editor

contacts["Joe Smith"][:email] = contact_data[0][0]
contacts["Joe Smith"][:address] = contact_data[0][1]
contacts["Joe Smith"][:phone] = contact_data[0][2]
contacts["Sally Johnson"][:email] = contact_data[1][0]
contacts["Sally Johnson"][:address] = contact_data[1][1]
contacts["Sally Johnson"][:phone] = contact_data[1][2]

Video Walkthrough

Duration: 7:42

Exercise 12

Using the hash you created from the previous exercise, demonstrate how you would access Joe's email and Sally's phone number.

View Our Solution Work in Code Editor

puts "Joe's email is: #{contacts["Joe Smith"][:email]}"
puts "Sally's phone number is: #{contacts["Sally Johnson"][:phone]}"

Video Walkthrough

Duration: 2:23

Exercise 13

Use Ruby's Array method delete_if and String method start_with? to delete all of the strings that begin with an "s" in the following array.

arr = ['snow', 'winter', 'ice', 'slippery', 'salted roads', 'white trees']

Then recreate the arr and get rid of all of the strings that start with "s" or start with "w".

View Our Solution Work in Code Editor

arr.delete_if { |str| str.start_with?("s") }

arr.delete_if { |str| str.start_with?("s", "w") }

Video Walkthrough

Duration: 2:43

Errata:

  • The narrator talks about deleting words. We are actually deleting strings, some of which contain more than one word.
  • The code in the video uses the variable word where the above solution uses str.
Exercise 14

Take the following array:

a = ['white snow', 'winter wonderland', 'melting ice',
     'slippery sidewalk', 'salted roads', 'white trees']

and turn it into a new array that consists of strings containing one word. (ex. ["white snow", etc...]["white", "snow", etc...]. Look into using Array's map and flatten methods, as well as String's split method.

View Our Solution Work in Code Editor

a = ['white snow', 'winter wonderland', 'melting ice',
     'slippery sidewalk', 'salted roads', 'white trees']
a = a.map { |pairs| pairs.split }
a = a.flatten
p a

Video Walkthrough

Duration: 2:22

Exercise 15

What will the following program output?

hash1 = {shoes: "nike", "hat" => "adidas", :hoodie => true}
hash2 = {"hat" => "adidas", :shoes => "nike", hoodie: true}

if hash1 == hash2
  puts "These hashes are the same!"
else
  puts "These hashes are not the same!"
end

View Our Solution Work in Code Editor

These hashes are the same!

Video Walkthrough

Duration: 2:16

Exercise 16

Challenge: In exercise 11, we manually set the contacts hash values one by one. Now, programmatically loop or iterate over the contacts hash from exercise 11, and populate the associated data from the contact_data array. Hint: you will probably need to iterate over ([:email, :address, :phone]), and some helpful methods might be the Array shift and first methods.

Note that this exercise is only concerned with dealing with 1 entry in the contacts hash, like this:

contact_data = ["joe@email.com", "123 Main st.", "555-123-4567"]
contacts = {"Joe Smith" => {}}

As a bonus, see if you can figure out how to make it work with multiple entries in the contacts hash.

Exercises marked as challenges can be very difficult. Don't get discouraged if you can't complete it, but do make the attempt. Even if you can't solve the exercise, be sure to read through the solution, if one is provided.

View Our Solution Work in Code Editor

contact_data = ["joe@email.com", "123 Main st.", "555-123-4567"]
contacts = {"Joe Smith" => {}}
fields = [:email, :address, :phone]

contacts.each do |name, hash|
  fields.each do |field|
    hash[field] = contact_data.shift
  end
end

Solution to bonus, where we can work with multiple entries in the contacts hash:

contact_data = [["joe@email.com", "123 Main st.", "555-123-4567"],
            ["sally@email.com", "404 Not Found Dr.", "123-234-3454"]]
contacts = {"Joe Smith" => {}, "Sally Johnson" => {}}
fields = [:email, :address, :phone]

contacts.each_with_index do |(name, hash), idx|
  fields.each do |field|
    hash[field] = contact_data[idx].shift
  end
end

Video Walkthrough

Duration: 7:28

Hi! I'm LSBot. I'm here to help you understand this chapter content with fast , focused answers. Any code from the editor will be automatically included with your question.

Ask me about concepts, examples, or anything you'd like clarified from this chapter. I can explain complex topics, provide examples, or help connect ideas.

Switch to Deep Dive mode if you want comprehensive answers across the entire curriculum. Responses may take longer, but I'll draw on the entire Launch School curriculum to give you a fuller picture.

Want to know more? Refer to the LSBot User Guide .

GitHub Repository Submission

When using GitHub mode, paste your repository URL below and click Save URL to store it. The saved URL will be automatically included with every message you send until you choose to clear it. Learn more

Your GitHub repository URL is saved. LSBot will automatically fetch your latest code from this repository for each message. To change the URL, clear it first and save a new one.
Output
No output yet. Click "Run Code" to execute your code.