add method(compact, compact!) and test of Hash to mruby-hash-ext
MODIFY
mrbgems/mruby-hash-ext/mrblib/hash.rb
mrbgems/mruby-hash-ext/mrblib/hash.rb
@@ -114,6 +114,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

MODIFY
mrbgems/mruby-hash-ext/test/hash.rb
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")

add method(compact, compact!) and test of Hash to mruby-hash-ext