Consider the following Ruby code that manipulates arrays. What will it print?
arr = [1, 2, 3, 4] arr << 5 arr.pop puts arr.length
Remember that << adds an element and pop removes the last element.
The array starts with 4 elements. Adding 5 makes it 5 elements. Then pop removes the last element (5), so the length returns to 4.
Which of the following best explains why arrays are fundamental in Ruby?
Think about how you keep a list of things in order.
Arrays let you keep many items in order and access them by their position, which is essential for many programming tasks.
Look at this Ruby code snippet. What error will it raise when run?
arr = [10, 20, 30] puts arr[5].to_s.length
What does Ruby return when you access an array index that does not exist?
Accessing an out-of-range index returns nil. Calling to_s on nil returns an empty string, whose length is 0.
What will this Ruby code print?
arr = [1, 2, 3, 4] new_arr = arr.map { |x| x * 2 if x.even? } puts new_arr.compact.sum
Remember that map keeps the same size and compact removes nil values.
Only even numbers (2 and 4) are doubled to 4 and 8. Odd numbers become nil. After compact, the array is [4, 8]. Their sum is 12.
Given this Ruby code, how many items does result contain?
arr = [1, 2, 3, 4, 5] result = arr.select.with_index { |val, idx| val > idx }
Check each element: is the value greater than its index?
Indexes and values: (0,1), (1,2), (2,3), (3,4), (4,5). All values are greater than their indexes, so all 5 elements are selected.