Ruby Arrays Quiz

Ruby
0 Passed
0% acceptance

40 comprehensive questions exploring Ruby array manipulation, indexing, methods, and data structures — with 16 code examples covering array creation, slicing, transformation methods, and nested arrays in this cpp quiz.

40 Questions
~80 minutes
1

Question 1

How do you create a basic array in Ruby?

A
Using square brackets with comma-separated values
B
Only with the Array.new method
C
Using parentheses
D
Arrays cannot be created directly
2

Question 2

What is array indexing in Ruby and how does negative indexing work?

A
Accessing elements by position where negative indices count from the end (-1 is last element), providing flexible element access from both array ends without calculating length
B
Negative indices are not allowed
C
Negative indices start from the beginning
D
Indexing only works with positive numbers
3

Question 3

When processing a list of exam scores where you need to add a new score to the end, which array method should you use?

ruby
scores = [85, 92, 78]
scores.push(88)
A
push() adds element to array end, modifying the original array in place and returning the modified array, perfect for accumulating data without creating new array objects
B
Use unshift to add to the end
C
Use + operator for adding elements
D
Arrays cannot be modified after creation
4

Question 4

How does array slicing work with ranges in Ruby?

A
Using range syntax [start..end] or [start...end] to extract subarrays, where inclusive range includes end index while exclusive range excludes it, enabling precise subarray extraction
B
Slicing only works with single indices
C
Ranges cannot be used for slicing
D
Slicing always includes the end index
5

Question 5

What is the difference between map and select methods in Ruby arrays?

ruby
numbers = [1, 2, 3, 4]
even_numbers = numbers.select(&:even?)
doubled = numbers.map { |n| n * 2 }
A
select returns filtered array with elements that match condition while map returns transformed array with same length but modified values, serving different data processing needs
B
They work identically
C
map filters elements, select transforms them
D
Both methods modify the original array
6

Question 6

In a shopping cart application where items are frequently added and removed from the end, how should you handle the data structure?

A
Use push for adding items and pop for removing, leveraging array's efficient end operations for stack-like behavior that minimizes array copying and maintains performance
B
Always use unshift and shift
C
Use + and - operators
D
Avoid modifying arrays in shopping applications
7

Question 7

What does the pop method do and what does it return?

A
Removes and returns the last element from array, modifying the array in place, which enables stack operations and efficient element removal without indexing calculations
B
Removes the first element
C
Returns the last element without removing it
D
Adds elements to the array
8

Question 8

How do you create nested arrays (multidimensional arrays) in Ruby?

ruby
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
element = matrix[1][2]
A
Create array of arrays using nested square brackets, accessing elements with multiple indices, enabling matrix-like data structures and hierarchical data organization
B
Nested arrays are not supported
C
Use special multidimensional syntax
D
Arrays can only be one-dimensional
9

Question 9

What is the difference between inclusive and exclusive ranges when converting to arrays?

A
Inclusive range (1..5).to_a includes end value while exclusive range (1...5).to_a excludes end value, affecting array length and boundary conditions in iteration and slicing operations
B
They create identical arrays
C
Exclusive ranges are not supported
D
Inclusive ranges exclude the end value
10

Question 10

When processing a queue of customer service requests where new requests are added to the end and processed from the front, which methods should you use?

A
Use push to add requests and shift to remove from front, implementing FIFO queue behavior that maintains request order and enables fair processing of customer service tickets
B
Use push and pop
C
Use unshift and shift
D
Queues cannot be implemented with arrays
11

Question 11

How does the unshift method work compared to push?

ruby
arr = [2, 3]
arr.unshift(1)
# arr is now [1, 2, 3]
A
unshift adds element to array beginning while push adds to end, both modifying in place but affecting different positions and shifting existing elements when adding to front
B
They work identically
C
unshift removes elements
D
push adds to the beginning
12

Question 12

In a data analysis application processing sensor readings stored in arrays, how would you filter out invalid readings below a threshold?

A
Use select with block condition to filter readings, creating new array with only valid data, enabling clean data processing pipelines without modifying original sensor data collection
B
Use map to filter readings
C
Use push to remove invalid readings
D
Invalid readings cannot be filtered
13

Question 13

What happens when you access an array index that is out of bounds?

A
Returns nil instead of raising exception, providing safe array access that allows checking for missing elements without error handling, though this can mask programming errors
B
Raises an IndexError exception
C
Returns the last element
D
Returns zero
14

Question 14

How do you convert a range of numbers directly to an array?

ruby
numbers = (1..10).to_a
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
A
Call to_a method on range object to convert to array, enabling enumeration and array operations on numeric sequences generated from range literals
B
Ranges automatically convert to arrays
C
Use Array.new with range
D
Range to array conversion is not supported
15

Question 15

When implementing a stack data structure where the last added item is processed first, which array methods provide the correct behavior?

A
Use push for adding items and pop for removing, implementing LIFO behavior essential for undo operations, function call stacks, and backtracking algorithms with efficient end operations
B
Use push and shift
C
Use unshift and pop
D
Stacks cannot be implemented with arrays
16

Question 16

What does the shift method do in Ruby arrays?

ruby
queue = ['first', 'second', 'third']
next_item = queue.shift
# next_item = 'first', queue = ['second', 'third']
A
Removes and returns first element from array, modifying array in place, which enables queue operations and efficient front removal for sequential processing workflows
B
Removes the last element
C
Adds element to the beginning
D
Returns first element without removing it
17

Question 17

In a web application processing form parameters that arrive as arrays of values, how should you handle multiple selections from checkboxes?

A
Access the parameter as array directly since form data preserves array structure, enabling direct iteration and processing of multiple selections without additional parsing or conversion steps
B
Convert strings to arrays manually
C
Form data cannot contain arrays
D
Use string splitting for array data
18

Question 18

What is the difference between map and map! methods?

A
map returns new array with transformed elements while map! modifies original array in place, affecting performance and whether original data is preserved for later use
B
They work identically
C
map! creates new arrays
D
map modifies in place
19

Question 19

How do you access elements in nested arrays using multiple indices?

ruby
grid = [['a', 'b'], ['c', 'd']]
letter = grid[1][0]  # 'c'
A
Use chained bracket notation with multiple indices, first accessing outer array element then inner array element, enabling matrix-like access patterns for two-dimensional data structures
B
Nested arrays cannot be accessed with multiple indices
C
Use single index for nested access
D
Multiple indices cause syntax errors
20

Question 20

When processing large datasets where you need to transform each element without creating intermediate arrays, which method should you choose?

A
Use map! for in-place transformation to avoid memory allocation of new arrays, improving performance for large datasets by modifying elements directly without creating temporary objects
B
Always use map (non-destructive)
C
Use select for transformation
D
Memory usage doesn't matter for transformations
21

Question 21

What does the include? method check for arrays?

A
Returns true if array contains specified element, enabling efficient membership testing for validation, filtering, and conditional logic without manual iteration or indexing
B
Checks if array is empty
C
Returns array length
D
Checks element type
22

Question 22

In a game leaderboard system where scores need to be kept sorted as new scores are added, how should you maintain the sorted order?

A
Use sort! after adding new scores to maintain sorted order in place, ensuring leaderboard remains correctly ordered without creating new array objects for each update
B
Sort after every access
C
Keep scores unsorted
D
Use map to sort scores
23

Question 23

How does the compact method work on arrays?

ruby
data = [1, nil, 3, nil, 5]
clean = data.compact
# [1, 3, 5]
A
Returns new array with all nil elements removed, enabling clean data processing by eliminating missing values without affecting the original array's structure or other elements
B
Removes all elements
C
Converts nil to zero
D
Compacts array in place
24

Question 24

What is the behavior of the * operator (splat) when used with arrays?

ruby
numbers = [1, 2, 3]
all = [*numbers, 4, 5]
# [1, 2, 3, 4, 5]
A
Splat operator expands array into individual elements, enabling array concatenation, method arguments expansion, and flexible element manipulation in various contexts
B
Multiplies array elements
C
Creates nested arrays
D
Splat operator is not supported for arrays
25

Question 25

When implementing a circular buffer where you need to efficiently add elements and remove old ones when capacity is reached, which approach should you use?

A
Use push for adding and shift for removing old elements, maintaining fixed size by checking length after push and shifting when over capacity, enabling efficient FIFO buffer management
B
Use unshift and pop
C
Recreate array each time
D
Circular buffers cannot be implemented with arrays
26

Question 26

What does the flatten method do to nested arrays?

A
Recursively flattens nested arrays into single-dimensional array, removing all nesting levels and creating flat structure suitable for linear operations and simplified processing
B
Adds nesting levels
C
Flattens only one level
D
Flatten only works on strings
27

Question 27

In a data processing pipeline where you need to chain multiple array transformations, how should you combine map and select operations?

A
Chain methods with dot notation, applying transformations in sequence, enabling functional programming patterns where each method receives result of previous operation for clean data flow
B
Use separate variables for each step
C
Cannot chain map and select
D
Use loops for chaining
28

Question 28

How do you create an array with default values using Array.new?

ruby
zeros = Array.new(5, 0)
# [0, 0, 0, 0, 0]
A
Pass size and default value to Array.new, creating array with specified length where each element is initialized to the default value, useful for creating matrices and initialized collections
B
Array.new only creates empty arrays
C
Use [] syntax for default values
D
Default values are not supported
29

Question 29

What is the difference between uniq and uniq! methods?

A
uniq returns new array with duplicates removed while uniq! modifies original array in place, affecting whether original collection is preserved or transformed directly for memory efficiency
B
They work identically
C
uniq! creates new arrays
D
uniq modifies in place
30

Question 30

When processing API responses that contain arrays of objects with nested data structures, how should you extract specific fields from each object?

A
Use map to transform each object, extracting desired fields into new array structure, enabling data normalization and field selection for consistent API response processing and data presentation
B
Use select to extract fields
C
API responses cannot be processed
D
Use loops for field extraction
31

Question 31

What does the reverse method do to arrays and what type of operation is it?

ruby
original = [1, 2, 3]
reversed = original.reverse
# original unchanged, reversed = [3, 2, 1]
A
Returns new array with elements in reverse order without modifying original, providing safe reversal that preserves original data for comparison or further processing needs
B
Reverses array in place
C
Sorts array in ascending order
D
Removes elements
32

Question 32

In a caching system where you need to maintain a fixed number of recent items, how should you implement the cache replacement policy?

A
Use unshift for new items and pop to remove oldest when over capacity, implementing LRU-like behavior where most recent items are kept and oldest are discarded automatically
B
Use push and shift
C
Recreate cache array each time
D
Caching cannot be implemented with arrays
33

Question 33

How does the zip method work when combining multiple arrays?

ruby
names = ['Alice', 'Bob']
ages = [25, 30]
combined = names.zip(ages)
# [['Alice', 25], ['Bob', 30]]
A
Combines corresponding elements from multiple arrays into nested array structure, enabling parallel iteration and data correlation for multi-attribute data processing and table-like operations
B
Concatenates arrays end to end
C
Creates single flat array
D
Zip only works with two arrays
34

Question 34

When working with sparse arrays where most elements are nil or default values, how should you handle memory efficiently?

A
Use compact to remove nil values when processing, reducing memory usage during operations, though Ruby arrays inherently store nil values efficiently without special handling needed for most use cases
B
Sparse arrays require special data structures
C
Use different data types for sparse data
D
Memory efficiency doesn't matter for arrays
35

Question 35

What does the sample method do for arrays?

A
Returns randomly selected element from array, enabling random sampling for testing, game logic, and statistical operations without modifying the original array structure
B
Returns all elements
C
Sorts array randomly
D
Removes random elements
36

Question 36

In a task scheduling system where tasks have priorities and you need to process high-priority tasks first, how should you organize the task array?

A
Keep sorted by priority using sort! after additions, enabling efficient access to highest priority tasks at array start while maintaining sorted order for priority queue behavior
B
Process tasks randomly
C
Keep tasks unsorted
D
Priority scheduling cannot be implemented with arrays
37

Question 37

How does the transpose method work on arrays of arrays?

ruby
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = matrix.transpose
# [[1, 4], [2, 5], [3, 6]]
A
Converts rows to columns in matrix-like structure, enabling mathematical matrix operations and data perspective changes for analysis and visualization requirements
B
Flattens the array
C
Reverses each subarray
D
Transpose only works on numbers
38

Question 38

When implementing a sliding window algorithm for data analysis, how should you efficiently extract consecutive elements?

A
Use range slicing [start..end] to extract window segments, enabling efficient subarray access for moving window calculations without array copying or complex indexing logic
B
Use map for window extraction
C
Sliding windows require loops only
D
Use select for window operations
39

Question 39

What does the rotate method do to arrays?

A
Returns new array with elements rotated by specified positions, enabling circular shifting for ring buffer implementations and data rearrangement without modifying original array
B
Rotates elements in place
C
Reverses the array
D
Sorts the array
40

Question 40

Considering Ruby's array handling ecosystem as a whole, what fundamental advantage do Ruby arrays provide compared to primitive arrays in other languages?

A
Ruby combines dynamic sizing with rich built-in methods and flexible literal syntax, creating an ecosystem where collection manipulation feels natural while maintaining performance through optimized C implementation and garbage collection
B
Faster processing speed only
C
Automatic type conversion
D
Simpler syntax only