mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
Add Hash#invert
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user