flat_map to flatten nested arrays?nested = [[1, 2], [3, 4], [5]] result = nested.flat_map { |arr| arr } puts result.inspect
flat_map maps and then flattens one level.The flat_map method applies the block to each element and then flattens the result by one level. Here, each element is an array, and the block returns it as is, so the result is a single flattened array with all elements.
flat_map to transform and flatten nested arrays?nested = [[1, 2], [3, 4], [5]] result = nested.flat_map { |arr| arr.map { |x| x * 2 } } puts result.inspect
flat_map flattens the result.The inner map doubles each number in the sub-arrays. Then flat_map flattens the resulting arrays into one array.
flat_map incorrectly?nested = [[1, 2], [3, 4], [5]] result = nested.flat_map do |arr| arr.each do |x| x * 2 end end puts result.inspect
flat_map.The each method iterates but returns the original sub-array arr. The x * 2 expressions are evaluated but their values are discarded. Thus, the block returns arr, and flat_map flattens the nested array without transformation into [1, 2, 3, 4, 5].
map and flat_map in Ruby?map applies the block and returns an array of the results, which can be nested arrays. flat_map applies the block and then flattens the result by one level, combining nested arrays into a single array.
flat_map twice to flatten a deeply nested array?nested = [[[1, 2], [3]], [[4, 5]], [6]] result = nested.flat_map { |arr| arr.flat_map { |x| x } } puts result.inspect
flat_map flattens one level after mapping.The first flat_map maps each sub-array and flattens one level, then the inner flat_map flattens the next level. Together they flatten the nested arrays into a single flat array.