0
0
Rubyprogramming~5 mins

Array creation methods in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AAn error
B[0, 0, 0, 0]
C[nil, nil, nil, nil]
D[[], [], [], []]
How do you create an array of 3 empty arrays, each a separate object?
AArray.new(3, [])
BArray.new(3) { [] }
C[[], [], []]
DBoth B and C
What does (5..8).to_a produce?
A[5, 6, 7, 8]
B[5, 6, 7]
C[6, 7, 8]
DAn error
What is the result of Array.new(3, 'a')?
A['a', 'b', 'c']
B['a', 'a', 'a']
C[nil, nil, nil]
DAn error
Which method creates an empty array?
AAll of the above
BArray.new(0)
CArray.new
D[]
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.