summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-hash-ext/mrblib/hash.rb
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2018-08-06 16:37:27 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2018-08-06 16:40:19 +0900
commit62e8e910b2905c9b7c964ad4e21c127f7ff3a706 (patch)
tree82903e98a00df58e2b3fdd25721c6b832fec212e /mrbgems/mruby-hash-ext/mrblib/hash.rb
parent0dca6206c1920d388fbf4d125c5984b1af530f2b (diff)
downloadmruby-62e8e910b2905c9b7c964ad4e21c127f7ff3a706.tar.gz
mruby-62e8e910b2905c9b7c964ad4e21c127f7ff3a706.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.rb35
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
##