0
0
Rubyprogramming~10 mins

Why Ruby prefers iterators over loops - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to iterate over the array using an iterator.

Ruby
numbers = [1, 2, 3, 4]
numbers.[1] do |num|
  puts num
end
Drag options to blanks, or click blank then click option'
Aeach
Bfor
Cwhile
Dloop
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'for' which is a loop keyword, not an iterator method.
Using 'while' which is a loop structure, not a method on arrays.
2fill in blank
medium

Complete the code to sum all elements using an iterator.

Ruby
numbers = [1, 2, 3, 4]
sum = 0
numbers.[1] do |num|
  sum += num
end
puts sum
Drag options to blanks, or click blank then click option'
Auntil
Bfor
Ceach
Dwhile
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'for' which is a loop, not an iterator method.
Using 'while' or 'until' which are loop keywords, not methods.
3fill in blank
hard

Fix the error in the iterator method name.

Ruby
fruits = ['apple', 'banana', 'cherry']
fruits.[1] do |fruit|
  puts fruit.capitalize
end
Drag options to blanks, or click blank then click option'
Aeach
Beachh
Cfor
Dloop
Attempts:
3 left
💡 Hint
Common Mistakes
Typing 'eachh' with an extra 'h'.
Using 'for' which is a loop keyword, not a method.
4fill in blank
hard

Complete the code to create a hash with word lengths for words longer than 3 letters.

Ruby
words = ['cat', 'house', 'dog', 'elephant']
lengths = words.inject({}) { |acc, word|
  if word.length [1] 3
    acc.merge({word=> word.length})
  end
  acc
}
Drag options to blanks, or click blank then click option'
A:
B>
C<
D=>
Attempts:
3 left
💡 Hint
Common Mistakes
Using ':' instead of '=>', which is Python syntax.
Using '<' instead of '>' in the condition.
5fill in blank
hard

Fill both blanks to select even numbers and square them in a hash.

Ruby
numbers = [1, 2, 3, 4, 5]
even_squares = numbers.inject({}) { |acc, num|
  if num % 2 [2] 0
    acc.merge({num=> num[1] 2})
  end
  acc
}
Drag options to blanks, or click blank then click option'
A=>
B**
C==
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using ':' instead of '=>' for hashes.
Using '+' instead of '**' for squaring.
Using '=' instead of '==' for comparison.