Episode 17c - Creating Arrays With Loops

In the previous examples, we have been using the "each" method to puts information about each item to the screen. Sometimes we want to collect the information in a variable instead of just puts the information to the screen. You can use the "each" method with an array to build a brand new array. For example, if you had an array of numbers and wanted to create a new array of numbers where each number is doubled, you can use this code:

numbers = [3, 4, 2, 1]
doubled_numbers = []
numbers.each do |number|
  doubled_numbers << number * 2
end
p doubled_numbers

The result should be:

[6, 8, 4, 2]

Note that we're using p doubled_numbers instead of puts doubled_numbers. This is because the puts statement tries to make the output look pretty, but it makes it hard to see the actual array. The p statement is better when you want to see the raw data like an array.

Exercises:

  1. Start with the array
    words = ["soccer", "basketball", "tennis"]
    Use the "each" method to create a new array with every word in capital letters. The result should be:
    ["SOCCER", "BASKETBALL", "TENNIS"]
    Note: be sure to use a p statement instead of a puts statement to see the actual array!
  2. Start with the array
    numbers = [23, 1, 34, 100, 9, 10, 23]
    Use the "each" method to create a new array with numbers less than 10. The result should be:
    [1, 9]
    Note: be sure to use a p statement instead of a puts statement to see the actual array!
  3. Start with the arrays
    girls = ["yumiko", "jessica", "carla"]
    boys = ["miguel", "aaron", "nico"]
    Use the "each" method to create a new array with all the names in a single array. The result should be:
    ["yumiko", "jessica", "carla", "miguel", "aaron", "nico"]
    Note: be sure to use a p statement instead of a puts statement to see the actual array! Also note that the order of the names doesn't matter for this exercise.