2
3

フロントエンドでのdigメソッドの使い方

Posted at

digメソッドとは

digメソッドは、Rubyのメソッドでありハッシュや配列などのデータ構造に対し、指定したキーまたはインデックスを使用して要素にアクセスできるメソッドです。

使い方

例えば、下記のデータへアクセスする場合には、下記のような方法でデータを取得できます。

data = {
  user: {
    name: "kaihatu tarou",
    address: {
      country: "Japan",
      region: "aichi"
    },
    orders: [
      { id: 1, product: "1" },
      { id: 2, product: "2" }
    ]
  }
}
name = data.dig(:user, :name)
# => "kaihatu tarou"

下記のように、他のキーと値が含まれる場合でも、digメソッドを使用することができます。以下のコードでは、item_hash の中にある status_id キーに対応する値の "1 (0から数えた場合)" 番目の値を比較する処理が実行されます。

item_hash = {
  "status_id" => [10, 2, 7],
  "other_key" => "example",
  "more_keys" => [1, 2, 3]
}
item_hash.dig("status_id", 1) == 2

item_hash.dig("status_id", 1000) == 1
# => nil

特徴

digメソッドの特徴としては、存在しない要素にアクセスするとnilが返されることです。
これにより、安全に要素へアクセスできます。

array = [A, B, C]
result = array.dig(5)
# => nil
item_hash = {
  "status_id" => [10, 2, 7],
  "other_key" => "example",
  "more_keys" => [1, 2, 3]
}

item_hash.dig("status_id", 1000) == 1
# => nil

参考サイト:
https://wingdoor.co.jp/blog/%E3%80%90ruby%E3%80%91dig%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6/

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