0
0
Rubyprogramming~10 mins

Each as the primary iterator in Ruby - Interactive Code Practice

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

Complete the code to print each number in the array.

Ruby
numbers = [1, 2, 3, 4, 5]
numbers.[1] do |num|
  puts num
end
Drag options to blanks, or click blank then click option'
Aeach
Bmap
Cselect
Dreduce
Attempts:
3 left
💡 Hint
Common Mistakes
Using map instead of each when you only want to perform an action without creating a new array.
2fill in blank
medium

Complete the code to collect squares of numbers using each.

Ruby
numbers = [1, 2, 3, 4]
squares = []
numbers.[1] do |n|
  squares << n * n
end
puts squares
Drag options to blanks, or click blank then click option'
Areduce
Bmap
Cselect
Deach
Attempts:
3 left
💡 Hint
Common Mistakes
Using map and expecting the original array to change.
3fill in blank
hard

Fix the error in the code to print each key and value from the hash.

Ruby
person = {name: "Alice", age: 30}
person.[1] do |key, value|
  puts "#{key}: #{value}"
end
Drag options to blanks, or click blank then click option'
Amap
Beach
Cselect
Dreduce
Attempts:
3 left
💡 Hint
Common Mistakes
Using map which returns a new array instead of iterating for side effects.
4fill in blank
hard

Fill both blanks to iterate over an array and print each element with its index.

Ruby
fruits = ["apple", "banana", "cherry"]
fruits.[1].[2] do |fruit, index|
  puts "#{index}: #{fruit}"
end
Drag options to blanks, or click blank then click option'
Aeach_with_index
Bmap
Ceach
Dselect
Attempts:
3 left
💡 Hint
Common Mistakes
Using only each without index, or using map which returns a new array.
5fill in blank
hard

Fill all three blanks to create a hash with word lengths for words longer than 3 letters.

Ruby
words = ["cat", "house", "dog", "elephant"]
lengths = {}
words.[1] do |[2]|
  if [2].length > 3
    lengths[[3]] = [3].length
  end
end
puts lengths
Drag options to blanks, or click blank then click option'
Aeach
Bword
Cselect
Dreduce
Attempts:
3 left
💡 Hint
Common Mistakes
Using a transforming method like select or map instead of each for building the hash manually.
Inconsistent block parameter names across the block.