LoginSignup
0
0

[Ruby] 配列・ハッシュの相互変換

Last updated at Posted at 2023-08-31

目的

現在携わっているRails + Vue.jsのプロジェクトで、Railsで配列をハッシュにしてVue.jsに渡したいときがあったので、その方法についてまとめる。

ハッシュ -> 配列

h = {one: 1, two: 2, three: 3}

# キーや値の取り出し
p h.keys   #=> [:one, :two, :three]
p h.values  #=> [1, 2, 3]

# キーをシンボルにして返す、キーに戻す
p s = h.keys.map {|e| e.to_s }  #=> ["one", "two", "three"]
p s.map { |e| e.to_sym }  #=> [:one, :two, :three]

# 配列にする
p h.flatten  #=> [:one, 1, :two, 2, :three, 3]

# [キー、値]を要素とする配列に変換
p h.to_a  #=> [[:one, 1], [:two, 2], [:three, 3]]

# [[キー、...],[値、...]]の配列に変換
p h.to_a.transpose  #=> [[:one, :two, :three], [1, 2, 3]]

flattenメソッド

多次元の配列やハッシュを平坦化(1次元配列)にするためのメソッド

ary = [1, 2, [ 3, 4, 5, [6, 7,[8, 9]], 10]]
p ary.flatten  #=> [1, 2, 3, 4, 5 ,6 ,7 ,8 ,9 ,10]

# 引数で何階層目まで平坦化するかを指定できる
p ary.flatten(1)  #=> [1, 2, 3, 4, 5, [6, 7, [8, 9]], 10]
p ary.flatten(2)  #=> [1, 2, 3, 4, 5, 6, 7, [8, 9], 10]

transposeメソッド

行と列を入れ替えた新しい配列を返す

[[1,2],[3,4],[5,6]].transpose
#=> [[1,3,5],[2,4,6]]

配列 -> ハッシュ

a = ["one", 1, "two", 2, "three", 3]
b = [["one", 1], ["two", 2], ["three", 3]]
c = [["one", "two", "three"], [1, 2, 3]]

# ハッシュ変換
p Hash[*a]  #=> {"one"=>1, "two"=>2, "three"=>3}

# [[キー, 値], ...]の配列から変換
p Hash[*b.flatten]  #=> {"one"=>1, "two"=>2, "three"=>3}
p b.to_h  #=> {"one"=>1, "two"=>2, "three"=>3}

# [[キー, ...], [値, ...]]の配列から変換
p Hash[*c.transpose.flatten]  #=> {"one"=>1, "two"=>2, "three"=>3}
p c.transpose.to_h

# キー配列と値の配列から変換
keys = ["one", "two", "three"]
values = [1, 2, 3]
p Hash[*[keys, values].transpose.flatten]  #=> {"one"=>1, "two"=>2, "three"=>3}
p [keys, values].transpose.to_h  #=> {"one"=>1, "two"=>2, "three"=>3}
p keys.zip(values).to_h

*(splat演算子)

配列を展開する演算子

ary = [1, 2, 3]
p [ary]  #=> [[1, 2, 3]]
p [*ary]  #=> [1, 2, 3]

参考にさせていただいた記事

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