From 4d46f366acbba00de1a56c2d3df85fceaaecd1a0 Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 9 Aug 2017 19:18:02 +0900 Subject: add method(compact, compact!) and test of Hash to mruby-hash-ext --- mrbgems/mruby-hash-ext/mrblib/hash.rb | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'mrbgems/mruby-hash-ext/mrblib') 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 @@ -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 -- cgit v1.2.3