Commit 28a858c1 authored by Jun Hiroe's avatar Jun Hiroe

Add Hash#flatten

parent e9e4c133
...@@ -100,4 +100,24 @@ class Hash ...@@ -100,4 +100,24 @@ class Hash
end end
self self
end end
##
# call-seq:
# hash.flatten -> an_array
# hash.flatten(level) -> an_array
#
# Returns a new array that is a one-dimensional flattening of this
# hash. That is, for every key or value that is an array, extract
# its elements into the new array. Unlike Array#flatten, this
# method does not flatten recursively by default. The optional
# <i>level</i> argument determines the level of recursion to flatten.
#
# a = {1=> "one", 2 => [2,"two"], 3 => "three"}
# a.flatten # => [1, "one", 2, [2, "two"], 3, "three"]
# a.flatten(2) # => [1, "one", 2, 2, "two", 3, "three"]
#
def flatten(level=1)
self.to_a.flatten(level)
end
end end
...@@ -73,3 +73,12 @@ assert("Hash#delete_if") do ...@@ -73,3 +73,12 @@ assert("Hash#delete_if") do
} }
assert_equal(base.size, n) assert_equal(base.size, n)
end end
assert("Hash#flatten") do
a = {1=> "one", 2 => [2,"two"], 3 => [3, ["three"]]}
assert_equal [1, "one", 2, [2, "two"], 3, [3, ["three"]]], a.flatten
assert_equal [[1, "one"], [2, [2, "two"]], [3, [3, ["three"]]]], a.flatten(0)
assert_equal [1, "one", 2, [2, "two"], 3, [3, ["three"]]], a.flatten(1)
assert_equal [1, "one", 2, 2, "two", 3, 3, ["three"]], a.flatten(2)
assert_equal [1, "one", 2, 2, "two", 3, 3, "three"], a.flatten(3)
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment