Skip to content
Browse files

add Hash#{select/reject} to return Hash as 1.9

  • Loading branch information...
1 parent 22568f9 commit d060c8a713cbfd356fd3814339bf6248d76f3507 @matz matz committed Jun 2, 2012
Showing with 56 additions and 0 deletions.
  1. +56 −0 mrblib/hash.rb
View
56 mrblib/hash.rb
@@ -80,6 +80,62 @@ def merge(other, &block)
end
h
end
+
+ # 1.8/1.9 Hash#reject! returns Hash; ISO says nothing.
+ def reject!(&b)
+ keys = []
+ self.each_key{|k|
+ v = self[k]
+ if b.call(k, v)
+ keys.push(k)
+ end
+ }
+ return nil if keys.size == 0
+ keys.each{|k|
+ self.delete(k)
+ }
+ self
+ end
+
+ # 1.8/1.9 Hash#reject returns Hash; ISO says nothing.
+ def reject(&b)
+ h = {}
+ self.each_key{|k|
+ v = self[k]
+ unless b.call(k, v)
+ h[k] = v
+ end
+ }
+ h
+ end
+
+ # 1.9 Hash#select! returns Hash; ISO says nothing.
+ def reject!(&b)
+ keys = []
+ self.each_key{|k|
+ v = self[k]
+ unless b.call(k, v)
+ keys.push(k)
+ end
+ }
+ return nil if keys.size == 0
+ keys.each{|k|
+ self.delete(k)
+ }
+ self
+ end
+
+ # 1.9 Hash#select returns Hash; ISO says nothing.
+ def select(&b)
+ h = {}
+ self.each_key{|k|
+ v = self[k]
+ if b.call(k, v)
+ h[k] = v
+ end
+ }
+ h
+ end
end
##

0 comments on commit d060c8a

Please sign in to comment.
Something went wrong with that request. Please try again.