give me a function that does this: input: [1,[2,3,null,4],[null],5] output: [1,2,3,4,5] in ruby

To solve this problem, we can use recursion to flatten the given array. Here's a Ruby function that takes an input array and returns a flattened array:

main.rb
def flatten_array(arr)
  result = []
  arr.each do |element|
    if element.is_a?(Array)
      result += flatten_array(element)
    elsif element
      result << element
    end
  end
  result
end
197 chars
12 lines

This function takes an array as input and initializes an empty array called result to store the flattened array. It then iterates over each element of the input array. If an element is an array, it recursively calls the flatten_array function on that element and concatenates the result with the result array. If the element is not an array and not nil, it is added to the result array directly.

Here's an example usage:

main.rb
input = [1,[2,3,nil,4],[nil],5]
output = flatten_array(input)
puts output.inspect
82 chars
4 lines

Output:

main.rb
[1, 2, 3, 4, 5]
16 chars
2 lines

The inspect method is used to display the output array in a readable format.

Please note that this implementation assumes that null in the input list is equivalent to nil.

related categories

gistlibby LogSnag