Commit a9488618 authored by Yukihiro "Matz" Matsumoto's avatar Yukihiro "Matz" Matsumoto

Merge pull request #2213 from suzukaze/add-hash.key

Add Hash#key
parents 0b23d10a dc4c042d
......@@ -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
......@@ -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
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment