Episode 17a - Synthesis: Arrays Plus More

You can use the "each" method combined with conditionals to filter items from an array. For example, if you had an array of words and only wanted to print out words less than 5 characters, you can use this code:

words = ["dog", "canary", "basketball", "sun", "moon"]
words.each do |word|
  if word.length < 5
    puts word
  end
end

The output of this code is:

dog
sun
moon

Exercises:

  1. Start with the array
    numbers = [4, 9, 2, 1, 12, 3, 8]
    Use the "each" method to only print out the numbers greater than 5. The result should be:
    9
    12
    8
  2. Start with the array
    names = ["Ada", "Charles", "Adam", "Aaron", "Michelle"]
    Use the "each" method to only print out the names that start with "A". (Hint: use the string "start_with?" method.). The result should be:
    Ada
    Adam
    Aaron
  3. Start with the array
    words = ["cat", "plane", "mission", "letter", "chair"]
    Use the "each" method to only print out words that don't have the letter "e". (Hint: use the string "include?" method.) The result should be:
    cat
    mission
    chair