Skip to content

Commit 9b6d1aa

Browse files
committed
Flatten array ruby solution.
1 parent c66fc97 commit 9b6d1aa

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

solutions/ruby/flatten_array.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Note that there is already an implementation in the core ruby library
2+
# http://ruby-doc.org/core-2.2.0/Array.html#method-i-flatten
3+
4+
def flatten_array(arr = [])
5+
return arr unless arr.is_a? Array
6+
7+
result = []
8+
arr.each do |elem|
9+
if elem.is_a? Array
10+
result += flatten_array(elem)
11+
else
12+
result << elem
13+
end
14+
end
15+
16+
result
17+
end
18+
19+
flatten_array([]) # => []
20+
flatten_array([[["a"]]]) # => ["a"]
21+
flatten_array([0, ["damn"], [[["a", "b"]]], 0]) # => [0, "damn", "a", "b", 0]

0 commit comments

Comments
 (0)