Ask LSBot

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.

    View Our 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

    Duration: 1:50

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

    View Our 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

    Duration: 1:52

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

    View Our 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

    Duration: 3:05

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

    View Our Solution

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

    Video Walkthrough

    Duration: 2:12

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

    View Our Solution

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

    Video Walkthrough

    Duration: 2:11

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

    View Our Solution

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

    Video Walkthrough

    Duration: 2:15

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

    View Our 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

    Duration: 1:20

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

    View Our Solution

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

    Video Walkthrough

    Duration: 1:27

  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

    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

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

    View Our Solution

    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

  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

    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

  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

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

    Video Walkthrough

    Duration: 2:23

  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

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

    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

  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

    These hashes are the same!
    

    Video Walkthrough

    Duration: 2:16

  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

    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

This conversation with LSBot is temporary. Sign up for free to save your conversations with LSBot.

Hi! I'm LSBot. I'm here to help you understand this chapter content with fast, focused answers.

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.

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

This conversation with LSBot is temporary. Sign up for free to save your conversations with LSBot.

Hi! I'm LSBot. I'm here to help you think through this exercise by providing hints and guidance, without giving away the solution.

You can ask me about your approach, request clarification on the problem, or seek help when you feel stuck.

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