0
0

More than 3 years have passed since last update.

Hashの配列から任意のキーで抜き出す【Ruby】

Last updated at Posted at 2021-07-30

Hashの配列から任意のキーで抜き出す

<Hash>
.pluck(:<key1>, :<Key2>, ...)
.map {|<Key1>, <Key2>, ...| {<Key1>: <Key1>, <Key1>: <Key2>, ...}}

以下みたいに書ける(Active Recordの場合select使えばいいんですけど)。

User
.find(1)
.pluck(:name, :desc)
.map {|n, d| {name: n, desc: d}}
#=> [{name: "a", desc: "This is a"}]

DRYに書くとこんなん。keys.zipのとこのkeysだけ変えればキーをすり替えられる。

def pluck_by(*keys)
    pluck(*keys).map {|obj| keys.zip(obj).to_h}
end
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