Exercises

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

Exercises

  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.

    Solution

    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

    Please register to play this video

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

    Solution

    # 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

    Please register to play this video

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

    Solution

    # 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

    Please register to play this video

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

    Solution

    # Append
    arr.push(11)
    # --- or ---
    arr << 11
    
    # Prepend
    arr.unshift(0)
    

    Video Walkthrough

    Please register to play this video

  5. Get rid of 11. And append a 3.

    Solution

    # Remove from end of array
    arr.pop
    
    # Append
    arr << 3
    # --- or ---
    arr.push(3)
    

    Video Walkthrough

    Please register to play this video

  6. Get rid of duplicates without specifically removing any one value.

    Solution

    # Does not modify calling object
    arr.uniq
    
    # Modifies the calling object
    arr.uniq!
    

    Video Walkthrough

    Please register to play this video

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

    Solution

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

    Video Walkthrough

    Please register to play this video

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

    Solution

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

    Video Walkthrough

    Please register to play this video

  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
    

    Solution

    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

    Please register to play this video

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

    Solution

    Yes

    # hash values as arrays
    hash = {names: ['bob', 'joe', 'susan']}
    
    # array of hashes
    arr = [{name: 'bob'}, {name: 'joe'}, {name: 'susan'}]
    

    Video Walkthrough

    Please register to play this video

  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"}
    #  }
    

    Solution

    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

    Please register to play this video

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

    Solution

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

    Video Walkthrough

    Please register to play this video

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

    Solution

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

    Video Walkthrough

    Please register to play this video

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

    Solution

    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

    Please register to play this video

  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
    

    Solution

    These hashes are the same!
    

    Video Walkthrough

    Please register to play this video

  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.

    Solution

    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

    Please register to play this video