0
1

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.

rubyの二重ハッシュ

Last updated at Posted at 2023-06-06
user_data = [
 {user: {profile: {name: 'うさぎさん'}}},
 {user: {profile: {name: 'うしさん'}}},
 {user: {profile: {name: 'ぶたさん'}}},
]

user_dataを利用して、全てのユーザーの名前だけが出力されるように、
rubyでうさぎさん うしさん ぶたさんだけを書き出したい。

user_data.each do |u|
  puts u[:user][:profile][:name]
end

となる。

二重ハッシュから特定の値を取得する場合は、取得したい値のキーまで連続して指定すると取れる。

ハッシュ[取得したい値のキー][取得したい値のキー]
取得したい値に対応するキーはname。
そのため、nameというキーまで連続して指定すると、うさぎさん, うしさん, ぶたさんという値を取れる。

ハッシュ[:user][:profile][:name]

配列の中にハッシュが格納されている。
そのため、each文でハッシュの1つ1つを取り出す必要がある。

多重階層にあるハッシュの値をまとめて取ってこれるdigメソッド使ってもいける。
user_data.each{ |u| puts u.dig(:user, :profile, :name) }

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?