Commit 53fcc40a authored by Yukihiro "Matz" Matsumoto's avatar Yukihiro "Matz" Matsumoto

Merge pull request #2192 from suzukaze/add-hash.invert

Add Hash#invert
parents 5921dd19 015f60fc
...@@ -120,4 +120,21 @@ class Hash ...@@ -120,4 +120,21 @@ class Hash
def flatten(level=1) def flatten(level=1)
self.to_a.flatten(level) self.to_a.flatten(level)
end end
##
# call-seq:
# hsh.invert -> new_hash
#
# Returns a new hash created by using <i>hsh</i>'s values as keys, and
# the keys as values.
#
# h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
# h.invert #=> {0=>"a", 100=>"m", 200=>"d", 300=>"y"}
#
def invert
h = Hash.new
self.each {|k, v| h[v] = k }
h
end
end end
...@@ -82,3 +82,16 @@ assert("Hash#flatten") do ...@@ -82,3 +82,16 @@ assert("Hash#flatten") do
assert_equal [1, "one", 2, 2, "two", 3, 3, ["three"]], a.flatten(2) assert_equal [1, "one", 2, 2, "two", 3, 3, ["three"]], a.flatten(2)
assert_equal [1, "one", 2, 2, "two", 3, 3, "three"], a.flatten(3) assert_equal [1, "one", 2, 2, "two", 3, 3, "three"], a.flatten(3)
end end
assert("Hash#invert") do
h = { 1 => 'one', 2 => 'two', 3 => 'three',
true => 'true', nil => 'nil' }.invert
assert_equal 1, h['one']
assert_equal true, h['true']
assert_equal nil, h['nil']
h = { 'a' => 1, 'b' => 2, 'c' => 1 }.invert
assert_equal(2, h.length)
assert_include(%w[a c], h[1])
assert_equal('b', h[2])
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