Permalink
Browse files

1.9.1: Backport Hash#assoc & Hash#rassoc, inspired by a patch from Ko…

…nstantin Haase
  • Loading branch information...
1 parent e95de8f commit c6aed5854ed9778a9b639dc801cadebda69f0d05 @marcandre committed Dec 2, 2011
Showing with 20 additions and 1 deletion.
  1. +1 −0 README.rdoc
  2. +19 −1 lib/backports/1.9.1/hash.rb
View
@@ -80,6 +80,7 @@ Additionally, the following Ruby 1.9 features have been backported:
* +round+
* Hash
+ * +assoc+, +rassoc+
* +try_convert+
* <tt>default_proc=</tt>
@@ -11,4 +11,22 @@ def try_convert(x)
def default_proc=(proc)
replace(Hash.new(&Backports.coerce_to(proc, Proc, :to_proc)).merge!(self))
end unless method_defined? :default_proc=
-end
+
+ # Standard in Ruby 1.9. See official documentation[http://ruby-doc.org/core-1.9/classes/Hash.html]
+ def assoc(key)
+ val = fetch(key) do
+ return find do |k, v|
+ [k, v] if k == key
+ end
+ end
+ [key, val]
+ end unless method_defined? :assoc
+
+
+ # Standard in Ruby 1.9. See official documentation[http://ruby-doc.org/core-1.9/classes/Hash.html]
+ def rassoc(value)
+ k = key(value)
+ v = fetch(k){return nil}
+ [k, fetch(k)] if k || v == value
+ end unless method_defined? :rassoc
+end

0 comments on commit c6aed58

Please sign in to comment.