a function to flatten a nested array, if it contains nil, removes the nils, if its elements are all nil, return empty array. in ruby

To flatten a nested array in Ruby, you can use recursion and the flatten method provided by the Array class. You can also add logic to remove nil values and return an empty array if all elements are nil. Here's an example implementation:

main.rb
def flatten_array(array)
  # Return an empty array if all elements are nil
  return [] if array.all?(&:nil?)

  # Remove nil values from the array
  array.compact!

  # Recursively flatten nested arrays
  array.map! do |element|
    element.is_a?(Array) ? flatten_array(element) : element
  end.flatten
end
307 chars
13 lines

Here's how you can use the flatten_array function:

main.rb
nested_array = [1, [2, [3, 4], nil, 5], nil, [nil, [6, nil], nil], []]
result = flatten_array(nested_array)
puts result.inspect
# Output: [1, 2, 3, 4, 5, 6]

empty_array = [[nil, nil], [nil, nil]]
result = flatten_array(empty_array)
puts result.inspect
# Output: []
266 chars
10 lines

In this example, the flatten_array function recursively flattens the nested array by using flatten on each element that is an array. It also checks for nil values and removes them using compact!. If all elements are nil, it returns an empty array.

related categories

gistlibby LogSnag