diff options
| author | Yukihiro "Matz" Matsumoto <[email protected]> | 2018-08-06 16:37:27 +0900 |
|---|---|---|
| committer | Yukihiro "Matz" Matsumoto <[email protected]> | 2018-08-25 09:17:46 +0900 |
| commit | 49d9fb8f41eff5e7d505f4be2f9d10f78188c97c (patch) | |
| tree | 41c60bb76164c91a37de92e8b2b138ffd41dfe72 /mrbgems/mruby-hash-ext/mrblib/hash.rb | |
| parent | 9409a2ff6d7c1467900278898d97c95dfe9ea229 (diff) | |
| download | mruby-49d9fb8f41eff5e7d505f4be2f9d10f78188c97c.tar.gz mruby-49d9fb8f41eff5e7d505f4be2f9d10f78188c97c.zip | |
Reimplement `Hash#compact!` to conform the standard behavior.
`Hash#compact!` should return `nil` if the receiver does not change.
Diffstat (limited to 'mrbgems/mruby-hash-ext/mrblib/hash.rb')
| -rw-r--r-- | mrbgems/mruby-hash-ext/mrblib/hash.rb | 35 |
1 files changed, 32 insertions, 3 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb index 549bca0a8..eaf54b871 100644 --- a/mrbgems/mruby-hash-ext/mrblib/hash.rb +++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb @@ -116,6 +116,31 @@ class Hash ## # call-seq: + # hsh.compact! -> hsh + # + # Removes all nil values from the hash. Returns the hash. + # Returns nil if the hash does not contain nil values. + # + # h = { a: 1, b: false, c: nil } + # h.compact! #=> { a: 1, b: false } + # + + def compact! + h = {} + keys = self.keys + nk = keys.select{|k| + self[k] != nil + } + return nil if (keys.size == nk.size) + nk.each {|k| + h[k] = self[k] + } + h + self.replace(h) + end + + ## + # call-seq: # hsh.compact -> new_hsh # # Returns a new hash with the nil values/key pairs removed @@ -125,9 +150,13 @@ class Hash # h #=> { a: 1, b: false, c: nil } # def compact - result = self.dup - result.compact! - result + h = {} + self.keys.select{|k| + self[k] != nil + }.each {|k| + h[k] = self[k] + } + h end ## |
