Add Hash#flatten

This commit is contained in:
Jun Hiroe
2014-05-04 21:03:48 +09:00
parent e9e4c13390
commit 28a858c17e
2 changed files with 29 additions and 0 deletions
+20
View File
@@ -100,4 +100,24 @@ class Hash
end
self
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
+9
View File
@@ -73,3 +73,12 @@ assert("Hash#delete_if") do
}
assert_equal(base.size, n)
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