Skip to content

Instantly share code, notes, and snippets.

@ibrado
Created June 10, 2018 14:01
Show Gist options
  • Save ibrado/33e3132a47cbf1eb873489ef61df822d to your computer and use it in GitHub Desktop.
Save ibrado/33e3132a47cbf1eb873489ef61df822d to your computer and use it in GitHub Desktop.
Flatten arrays, with compact option
#!/usr/bin/ruby
# A function to flatten arrays, optionally removing any nil elements
#
# ==== Parameters
# * +val+ - a value expected to be an array
# * +compact+ - set to true to remove nil elements
#
def flat(val, compact = false)
if val.is_a?(Array)
farr = []
val.each do |x|
if x.is_a?(Array)
farr += flat(x, compact)
else
farr << x if (!compact || compact && x)
end
end
# Or,
#compact ?
# val.each { |x|
# farr.push *(x.is_a?(Array) ? flat(x, compact) : x)
# }
#: val.each { |x|
# x.is_a?(Array) ? farr += flat(x, compact) : farr << x
#}
farr
else
val
end
end
x = [[1,2,[3]],4]
puts "Default"
puts "-------"
puts "Original: "+x.inspect
puts "Expected: "+x.flatten.inspect
puts " Result: "+flat(x).inspect
puts
x = [nil, [2, nil, [4]], 5, 6]
puts "Compact"
puts "-------"
puts "Original: "+x.inspect
puts "Expected: "+x.flatten.compact.inspect
puts " Result: "+flat(x, true).inspect
puts
x = 7
puts "Non-array"
puts "---------"
puts " Result: "+flat(x).inspect
puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment