0
0
Rubyprogramming~20 mins

Array creation methods in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Array Master
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 creating an array?
Consider the following Ruby code that creates an array. What will be printed?
Ruby
arr = Array.new(3, 'cat')
arr[0].upcase!
puts arr.inspect
A["cat", "cat", "cat"]
B["CAT", "CAT", "CAT"]
C["CAT", "cat", "cat"]
D["cat", "CAT", "cat"]
Attempts:
2 left
💡 Hint
Think about how Array.new with a single object argument shares the same object.
Predict Output
intermediate
2:00remaining
What does this Ruby array creation code output?
What will be the output of this Ruby code snippet?
Ruby
arr = Array.new(3) { 'dog' }
arr[0].upcase!
puts arr.inspect
A["DOG", "dog", "dog"]
B["DOG", "DOG", "DOG"]
C["dog", "dog", "dog"]
D["dog", "DOG", "dog"]
Attempts:
2 left
💡 Hint
Consider how the block form of Array.new creates new objects.
🧠 Conceptual
advanced
2:00remaining
Which Ruby array creation method creates independent objects?
Which of the following Ruby array creation methods ensures each element is a separate object?
AArray.new(4, [])
BArray.new(4)
CArray.new(4) { [] }
DArray.new(4, nil)
Attempts:
2 left
💡 Hint
Think about how the block form works compared to the single object argument.
Predict Output
advanced
2:00remaining
What is the output of this Ruby array creation and modification?
What will this Ruby code print?
Ruby
arr = Array.new(2) { |i| i * 2 }
arr[1] = 10
puts arr.inspect
A[0, 10]
B[0, 1]
C[0, 2]
D[2, 10]
Attempts:
2 left
💡 Hint
Remember the block argument is the index of the element.
🔧 Debug
expert
2:00remaining
Why does this Ruby array creation code raise an error?
This Ruby code raises an error. What is the cause?
Ruby
arr = Array.new(3) { |i| i + 'a' }
puts arr.inspect
ANameError because 'i' is undefined
BSyntaxError due to missing parentheses
CNo error, outputs ["0a", "1a", "2a"]
DTypeError because you cannot add an integer and a string
Attempts:
2 left
💡 Hint
Check the operation inside the block carefully.