0
0
Rubyprogramming~20 mins

Array methods (length, include?, flatten) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code using length?
Look at the array and the method used. What will be printed?
Ruby
arr = [1, 2, 3, 4, 5]
puts arr.length
A5
B4
C6
DError
Attempts:
2 left
💡 Hint
The length method tells how many items are in the array.
Predict Output
intermediate
2:00remaining
What does include? return here?
Check if the array contains the number 3.
Ruby
arr = [1, 2, 3, 4, 5]
puts arr.include?(3)
Afalse
BError
Cnil
Dtrue
Attempts:
2 left
💡 Hint
The method include? returns true if the item is found.
Predict Output
advanced
2:00remaining
What is the output of flatten on a nested array?
This array has arrays inside. What will flatten do?
Ruby
arr = [1, [2, 3], [4, [5, 6]]]
puts arr.flatten.inspect
A[1, [2, 3], [4, [5, 6]]]
B[1, 2, 3, 4, 5, 6]
C[1, 2, 3, 4, [5, 6]]
DError
Attempts:
2 left
💡 Hint
The flatten method removes all nested arrays and makes one flat array.
Predict Output
advanced
2:00remaining
What is the length of the array after flattening?
Check the length of the array after using flatten.
Ruby
arr = [[1, 2], [3, 4], 5]
flat_arr = arr.flatten
puts flat_arr.length
A5
B3
C4
DError
Attempts:
2 left
💡 Hint
Flattening removes nested arrays, so count all individual elements.
🧠 Conceptual
expert
2:00remaining
Which option causes an error when calling include??
One of these arrays will cause an error when calling include? with argument 3. Which one?
Aarr = [1, 2, 3]; arr.include?(3)
Barr = [nil, false]; arr.include?(3)
Carr = nil; arr.include?(3)
Darr = []; arr.include?(3)
Attempts:
2 left
💡 Hint
Think about what happens if the variable is not an array.