0
0

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 1 year has passed since last update.

入れ子のHashにおける値の取得

Posted at

目的

  • 入れ子構造の連想配列から任意の値を取得する

ポイント

  • 入れ子とは、オブジェクトの値にさらにオブジェクトを指定したもの
  • dig メソッドでも取得できる

具体例1


#以下の変数hashから、値"USA"を取得する

require "pry"

hash = {
  sports: {
    soccer: {
      origin: "England"
    },
    volleyball: {
      origin: "USA"
    }
  }
}

binding.pry

puts hash[:sports][:volleyball][:origin]

~実際の表示~
31: }
32: }
33:
34: binding.pry
35:
=> 36: p hash

[16] pry(main)> hash.class
=> Hash
[17] pry(main)> hash[:sports].class
=> Hash
[18] pry(main)> #Hashなので、keyの指定で値を取得できる
[19] pry(main)> hash[:sports][:volleyball][:origin]
=> "USA"

具体例2

# 以下の変数hashから、値"USA"を取得する

hash = {
  sports: {
    soccer: {
      origin: "England"
    },
    volleyball: {
      origin: "USA"
    }
  }
}

puts hash.dig(:sports, :volleyball, :origin)

~実際の表示~
USA

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?