diff options
Diffstat (limited to 'mrbgems/mruby-hash-ext/mrblib/hash.rb')
| -rw-r--r-- | mrbgems/mruby-hash-ext/mrblib/hash.rb | 34 |
1 files changed, 34 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 |
