summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-hash-ext/mrblib/hash.rb
diff options
context:
space:
mode:
authorJun Hiroe <[email protected]>2014-05-05 11:15:48 +0900
committerJun Hiroe <[email protected]>2014-05-05 11:15:48 +0900
commit015f60fcad03ec697d8489281b3718929d242b33 (patch)
tree117f96d308390de877849071de0d14805cf08d4d /mrbgems/mruby-hash-ext/mrblib/hash.rb
parent5921dd19c58862298cf8fc7df79b943152785d8d (diff)
downloadmruby-015f60fcad03ec697d8489281b3718929d242b33.tar.gz
mruby-015f60fcad03ec697d8489281b3718929d242b33.zip
Add Hash#invert
Diffstat (limited to 'mrbgems/mruby-hash-ext/mrblib/hash.rb')
-rw-r--r--mrbgems/mruby-hash-ext/mrblib/hash.rb17
1 files changed, 17 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