Commit 015f60fc authored by Jun Hiroe's avatar Jun Hiroe

Add Hash#invert

parent 5921dd19
......@@ -120,4 +120,21 @@ class Hash
def flatten(level=1)
self.to_a.flatten(level)
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
......@@ -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(3)
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