Recall & Review
beginner
How do you create an empty array in Ruby?
You create an empty array by using square brackets with nothing inside:
[].Click to reveal answer
beginner
What does
Array.new(3) do in Ruby?It creates a new array with 3 elements, all set to
nil by default: [nil, nil, nil].Click to reveal answer
beginner
How can you create an array with 5 zeros using
Array.new?Use
Array.new(5, 0). This creates an array with 5 elements, each set to 0: [0, 0, 0, 0, 0].Click to reveal answer
intermediate
What is the difference between
Array.new(3, []) and Array.new(3) { [] }?The first creates an array with 3 references to the same empty array (shared object). The second creates 3 separate empty arrays (different objects).
Click to reveal answer
beginner
How do you create an array from a range in Ruby?
Use the
to_a method on a range. For example, (1..5).to_a creates [1, 2, 3, 4, 5].Click to reveal answer
What does
Array.new(4) return?✗ Incorrect
Array.new(4) creates an array with 4 elements, all set to nil by default.How do you create an array of 3 empty arrays, each a separate object?
✗ Incorrect
Using a block with
Array.new(3) { [] } or writing [[], [], []] creates separate empty arrays.What does
(5..8).to_a produce?✗ Incorrect
The range
5..8 includes 5, 6, 7, and 8. to_a converts it to an array with these elements.What is the result of
Array.new(3, 'a')?✗ Incorrect
It creates an array with 3 elements, each set to the string 'a'.
Which method creates an empty array?
✗ Incorrect
All these create an empty array in Ruby.
Explain three different ways to create arrays in Ruby and when you might use each.
Think about empty arrays, arrays with repeated values, and arrays with unique objects.
You got /5 concepts.
Describe the difference between
Array.new(3, []) and Array.new(3) { [] } in Ruby.Consider what happens if you change one element inside the arrays.
You got /4 concepts.