summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-hash-ext
diff options
context:
space:
mode:
authorvvakame <[email protected]>2017-08-09 19:18:02 +0900
committervvakame <[email protected]>2017-08-09 19:18:02 +0900
commit4d46f366acbba00de1a56c2d3df85fceaaecd1a0 (patch)
tree2b3e1d2dc8adfee9db1ac4c68d99c94f82c21432 /mrbgems/mruby-hash-ext
parentf9c3ebd29d7410be209b3f22b9923f0f81f0141d (diff)
downloadmruby-4d46f366acbba00de1a56c2d3df85fceaaecd1a0.tar.gz
mruby-4d46f366acbba00de1a56c2d3df85fceaaecd1a0.zip
add method(compact, compact!) and test of Hash to mruby-hash-ext
Diffstat (limited to 'mrbgems/mruby-hash-ext')
-rw-r--r--mrbgems/mruby-hash-ext/mrblib/hash.rb34
-rw-r--r--mrbgems/mruby-hash-ext/test/hash.rb14
2 files changed, 48 insertions, 0 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb
index 846cba9ff..640f7daf5 100644
--- a/mrbgems/mruby-hash-ext/mrblib/hash.rb
+++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb
@@ -115,6 +115,40 @@ class Hash
alias update merge!
##
+ # call-seq:
+ # hsh.compact -> new_hsh
+ #
+ # Returns a new hash with the nil values/key pairs removed
+ #
+ # h = { a: 1, b: false, c: nil }
+ # h.compact #=> { a: 1, b: false }
+ # h #=> { a: 1, b: false, c: nil }
+ #
+ def compact
+ result = self.dup
+ result.compact!
+ result
+ end
+
+ ##
+ # call-seq:
+ # hsh.compact! -> hsh
+ #
+ # Removes all nil values from the hash. Returns the hash.
+ #
+ # h = { a: 1, b: false, c: nil }
+ # h.compact! #=> { a: 1, b: false }
+ #
+ def compact!
+ result = self.select { |k, v| !v.nil? }
+ if result.size == self.size
+ nil
+ else
+ self.replace(result)
+ end
+ end
+
+ ##
# call-seq:
# hsh.fetch(key [, default] ) -> obj
# hsh.fetch(key) {| key | block } -> obj
diff --git a/mrbgems/mruby-hash-ext/test/hash.rb b/mrbgems/mruby-hash-ext/test/hash.rb
index 2ae88c307..ca4e346fb 100644
--- a/mrbgems/mruby-hash-ext/test/hash.rb
+++ b/mrbgems/mruby-hash-ext/test/hash.rb
@@ -82,6 +82,20 @@ assert('Hash#values_at') do
assert_equal keys, h.values_at(*keys)
end
+assert('Hash#compact') do
+ h = { "cat" => "feline", "dog" => nil, "cow" => false }
+
+ assert_equal({ "cat" => "feline", "cow" => false }, h.compact)
+ assert_equal({ "cat" => "feline", "dog" => nil, "cow" => false }, h)
+end
+
+assert('Hash#compact!') do
+ h = { "cat" => "feline", "dog" => nil, "cow" => false }
+
+ h.compact!
+ assert_equal({ "cat" => "feline", "cow" => false }, h)
+end
+
assert('Hash#fetch') do
h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
assert_equal "feline", h.fetch("cat")