diff options
| author | Jun Hiroe <[email protected]> | 2014-05-05 11:15:48 +0900 |
|---|---|---|
| committer | Jun Hiroe <[email protected]> | 2014-05-05 11:15:48 +0900 |
| commit | 015f60fcad03ec697d8489281b3718929d242b33 (patch) | |
| tree | 117f96d308390de877849071de0d14805cf08d4d | |
| parent | 5921dd19c58862298cf8fc7df79b943152785d8d (diff) | |
| download | mruby-015f60fcad03ec697d8489281b3718929d242b33.tar.gz mruby-015f60fcad03ec697d8489281b3718929d242b33.zip | |
Add Hash#invert
| -rw-r--r-- | mrbgems/mruby-hash-ext/mrblib/hash.rb | 17 | ||||
| -rw-r--r-- | mrbgems/mruby-hash-ext/test/hash.rb | 13 |
2 files changed, 30 insertions, 0 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb index 1ebc540e8..48bade330 100644 --- a/mrbgems/mruby-hash-ext/mrblib/hash.rb +++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb @@ -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 diff --git a/mrbgems/mruby-hash-ext/test/hash.rb b/mrbgems/mruby-hash-ext/test/hash.rb index 7d8d66b4e..10880666e 100644 --- a/mrbgems/mruby-hash-ext/test/hash.rb +++ b/mrbgems/mruby-hash-ext/test/hash.rb @@ -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 |
