summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-hash-ext
diff options
context:
space:
mode:
authorJun Hiroe <[email protected]>2014-05-08 17:53:41 +0900
committerJun Hiroe <[email protected]>2014-05-09 00:46:33 +0900
commitdc4c042df5466287764bf46377ca9baa6690f198 (patch)
tree42a0e5d8917a36cb5583602edb1d278e83546f47 /mrbgems/mruby-hash-ext
parentc071ad13a9df20e8e030320eef0a483bf4e64932 (diff)
downloadmruby-dc4c042df5466287764bf46377ca9baa6690f198.tar.gz
mruby-dc4c042df5466287764bf46377ca9baa6690f198.zip
Add Hash#key
Diffstat (limited to 'mrbgems/mruby-hash-ext')
-rw-r--r--mrbgems/mruby-hash-ext/mrblib/hash.rb20
-rw-r--r--mrbgems/mruby-hash-ext/test/hash.rb9
2 files changed, 29 insertions, 0 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb
index a5f04e5e1..259b0fa12 100644
--- a/mrbgems/mruby-hash-ext/mrblib/hash.rb
+++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb
@@ -160,4 +160,24 @@ class Hash
end
self
end
+
+ ##
+ # call-seq:
+ # hsh.key(value) -> key
+ #
+ # Returns the key of an occurrence of a given value. If the value is
+ # not found, returns <code>nil</code>.
+ #
+ # h = { "a" => 100, "b" => 200, "c" => 300, "d" => 300 }
+ # h.key(200) #=> "b"
+ # h.key(300) #=> "c"
+ # h.key(999) #=> nil
+ #
+
+ def key(val)
+ self.each do |k, v|
+ return k if v == val
+ end
+ nil
+ end
end
diff --git a/mrbgems/mruby-hash-ext/test/hash.rb b/mrbgems/mruby-hash-ext/test/hash.rb
index 1334522ff..b9992fa96 100644
--- a/mrbgems/mruby-hash-ext/test/hash.rb
+++ b/mrbgems/mruby-hash-ext/test/hash.rb
@@ -102,3 +102,12 @@ assert("Hash#keep_if") do
h = { 1 => 2, 3 => 4, 5 => 6 }
assert_equal({ 1 => 2, 3=> 4, 5 =>6} , h.keep_if { true })
end
+
+assert("Hash#key") do
+ h = { "a" => 100, "b" => 200, "c" => 300, "d" => 300, nil => 'nil', 'nil' => nil }
+ assert_equal "b", h.key(200)
+ assert_equal "c", h.key(300)
+ assert_nil h.key(999)
+ assert_nil h.key('nil')
+ assert_equal 'nil', h.key(nil)
+end