0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RubyのHashでキーと値を入れ替える

Posted at

組み込みメソッド invert を使う

キーと値を入れ替えた新しいハッシュを作成して返す。
元のハッシュで値が重複していた場合、最後に定義されている値のみ残る。

hash1 = {main: "hamburger", side: "potato", drink: "cola"}
hash1.invert
#=> {"hamburger"=>:main, "potato"=>:side, "cola"=>:drink}

hash2 = {main: "hamburger", side: "hamburger", drink: "cola"}
hash2.invert
#=> {"hamburger"=>:side, "cola"=>:drink}

詳しくはこちら
https://docs.ruby-lang.org/ja/latest/method/Hash/i/invert.html

invert を使わない方法

あまり需要はないかもしれないが、Hash#each_with_object でも表現できる。

hash.each_with_object({}) do |(key, val), object|
  object[val] = key
end
# => {"hamburger"=>:main, "potato"=>:side, "cola"=>:drink}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?