LoginSignup
2
0

More than 5 years have passed since last update.

配列をハッシュに変換する方法

Posted at

基本的だけれども忘れがちな、配列をハッシュに変換する方法のメモ

配列の配列を変換 → Hash[ary] or Array#to_h

[[key0, val0], [key1, val1], ...]形式の配列をハッシュにする場合は、Hash[]の引数にそのまま突っ込むか、素直にto_hでOK

alist = [[1,"a"], [2,"b"], [3,["c"]]]
p Hash[alist]  # => {1=>"a", 2=>"b", 3=>["c"]}

一次元配列を変換 → Hash[*key_and_value]

[key0, val0, key1, val1, ...]形式の配列にはto_hは使えません。
この場合はHash[]で良いですが、上の場合と違い*で引数を展開する必要があります

ary = [1,"a", 2,"b", 3,["c"]]
p Hash[*ary]  # => {1=>"a", 2=>"b", 3=>["c"]}

Kernel#Hash

おまけで。
Kernel#Hashというメソッドがありますが、これは引数をto_hashで変換します(to_hはしてくれない)。
Arrayにはto_hashメソッドは定義されていないので、今回は利用できません。

ただし、例外で空配列の場合のみ空のハッシュが返されます。

Hash([1,"a", 2,"b", 3,["c"]])  # => TypeError: can't convert Array into Hash
Hash([[1,"a"], [2,"b"], [3,["c"]]])  # => TypeError: can't convert Array into Hash
Hash([])  # => {}

参考

singleton method Hash.[]
module function Kernel.#Hash

2
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
2
0