map to transform an array of numbers. What will be printed?numbers = [1, 2, 3, 4] result = numbers.map { |n| n * 3 } puts result.inspect
map creates a new array by applying the block to each element.The map method applies the block { |n| n * 3 } to each element, multiplying each number by 3. So the output is [3, 6, 9, 12].
collect with a conditional inside the block. What is the output?arr = [5, 10, 15, 20] result = arr.collect { |x| x > 10 ? x / 5 : x } puts result.inspect
The block checks if each element is greater than 10. If yes, it divides by 5; otherwise, it keeps the original value. So 15 becomes 3, 20 becomes 4, others stay the same.
map to transform an array but raises an error. What is the cause?arr = [1, 2, 3] result = arr.map do |x| x * 2 end result = result + 1 puts result.inspect
result is added to 1.The map returns an array, but result + 1 tries to add an integer to an array, causing a TypeError.
map, what will be printed?matrix = [[1, 2], [3, 4]] result = matrix.map { |row| row.map { |n| n + 1 } } puts result.inspect
The outer map goes through each row (array), and the inner map adds 1 to each number. So each number increases by 1.
arr = [1, 2, 3, 4, 5] result = arr.map { |x| x if x.even? } puts result.compact.size
map keeps the same number of elements, but some may be nil.The map returns an array with elements that are even numbers or nil for odd numbers. After compact, only even numbers remain. There are 2 even numbers (2 and 4), so size is 2.
However, the code prints result.compact.size, which is 2.
