Challenge - 5 Problems
Ruby Array Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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
Attempts:
2 left
💡 Hint
Think about how Array.new with a single object argument shares the same object.
✗ Incorrect
Using Array.new(3, 'cat') creates an array with three references to the same string object. When upcase! modifies the first element, it changes the shared string, so all elements show the change.
❓ Predict Output
intermediate2: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
Attempts:
2 left
💡 Hint
Consider how the block form of Array.new creates new objects.
✗ Incorrect
Using Array.new(3) { 'dog' } creates a new string object for each element. So modifying one element does not affect the others.
🧠 Conceptual
advanced2:00remaining
Which Ruby array creation method creates independent objects?
Which of the following Ruby array creation methods ensures each element is a separate object?
Attempts:
2 left
💡 Hint
Think about how the block form works compared to the single object argument.
✗ Incorrect
Array.new(4) { [] } calls the block 4 times, creating a new empty array each time. The other methods either share the same object or fill with nil.
❓ Predict Output
advanced2: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
Attempts:
2 left
💡 Hint
Remember the block argument is the index of the element.
✗ Incorrect
The block { |i| i * 2 } creates [0, 2]. Then arr[1] = 10 changes the second element to 10.
🔧 Debug
expert2: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
Attempts:
2 left
💡 Hint
Check the operation inside the block carefully.
✗ Incorrect
The block tries to add an integer i to a string 'a', which causes a TypeError in Ruby.