summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-hash-ext
diff options
context:
space:
mode:
authorJun Hiroe <[email protected]>2014-05-04 21:03:48 +0900
committerJun Hiroe <[email protected]>2014-05-04 21:14:13 +0900
commit28a858c17edd0c9939dd18d1ca82ff6a3cb42948 (patch)
tree8f41d698809afb80f10d8283cbbf47e2dd9d3f11 /mrbgems/mruby-hash-ext
parente9e4c13390eb5f135182449a951d6b6eec05b2e9 (diff)
downloadmruby-28a858c17edd0c9939dd18d1ca82ff6a3cb42948.tar.gz
mruby-28a858c17edd0c9939dd18d1ca82ff6a3cb42948.zip
Add Hash#flatten
Diffstat (limited to 'mrbgems/mruby-hash-ext')
-rw-r--r--mrbgems/mruby-hash-ext/mrblib/hash.rb20
-rw-r--r--mrbgems/mruby-hash-ext/test/hash.rb9
2 files changed, 29 insertions, 0 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb
index ce8fa3577..1ebc540e8 100644
--- a/mrbgems/mruby-hash-ext/mrblib/hash.rb
+++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb
@@ -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
diff --git a/mrbgems/mruby-hash-ext/test/hash.rb b/mrbgems/mruby-hash-ext/test/hash.rb
index 4c7dbb217..7d8d66b4e 100644
--- a/mrbgems/mruby-hash-ext/test/hash.rb
+++ b/mrbgems/mruby-hash-ext/test/hash.rb
@@ -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