52
46

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 5 years have passed since last update.

ArrayからHashに変換する方法いろいろ

Last updated at Posted at 2015-08-01

その1 キーとバリューが交互の配列

ary = [1, "ねずみ", 2, "うし", 3, "とら"]
h = Hash[*ary]

=>{1=>"ねずみ", 2=>"うし", 3=>"とら"}

配列を格納している変数aryの先頭に * をつけた場合、配列に入っている要素を全て代入する多重代入が行われます。

その2 キーとバリューのセットが配列になっている配列

ary = [[1, "ねずみ"], [2, "うし"], [3, "とら"]]
h = Hash[*ary.flatten]

=>{1=>"ねずみ", 2=>"うし", 3=>"とら"}

配列の中に配列が入っている場合flattenメソッドで平滑化すると、

=> [1, "ねずみ", 2, "うし", 3, "とら"]

このような配列(つまりその1と同じ)になります。

その3 キーとバリューがそれぞれ違う配列

key = [1, 2, 3]
value = ["ねずみ", "うし", "とら"]
ary = [key, value].transpose
h = Hash[*ary.flatten]

=>{1=>"ねずみ", 2=>"うし", 3=>"とら"}

配列が2つに分かれている場合、transposeメソッドで

=> [[1, "ねずみ"], [2, "うし"], [3, "とら"]]

このように、その2と同じ形になります。

参考

52
46
2

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
52
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?