mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
Add Hash#flatten
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user