简体   繁体   中英

Extracting only specific members from a Ruby hash

I would like to extract only the team_member_id and display_name from the below hash returned from dropbox api.

{"members"=>[{"profile"=>{"team_member_id"=>"dbmid:AACHnGyTHHna44224Ad-vVewFDJ9nzS7be9GJ6Tc", "account_id"=>"dbid:AAD234234234x2yGXHsG3guC04Fp8QPwUF9NDO55w", "email"=>"name@domain.com", "email_verified"=>true, "secondary_emails"=>[], "status"=>{".tag"=>"active"}, "name"=>{"given_name"=>"firstname", "surname"=>"lastname", "familiar_name"=>"first", "display_name"=>"firstname lastname", "abbreviated_name"=>"MM"}, "membership_type"=>{".tag"=>"full"}, "joined_on"=>"2017-01-02T20:58:20Z", "groups"=>["g:6fe6b5a111cfc0400000000000000005", "g:6fe6b5a111cfc04000000000000015a1", "g:6fe6b5a111cfc0400000000000002299", "g:6fe6b5a111cfc04000000000000043cb", "g:6fe6b5a111cfc0400000000000056eb3", "g:6fe6b5a111cfc0400000000000058122", "g:6fe6b5a111cfc0400000000000058248", "g:6fe6b5a111cfc04000000000002dd0d9", "g:6fe6b5a111cfc04000000000002dd650"], "member_folder_id"=>"1384307556"}, "role"=>{".tag"=>"team_admin"}}], "cursor"=>"AAAXuLKhvS_T97ZjALBH4A2MCQW_xOp9bu0tAwqGuY1zBg_C-UKVZoBDTQkhU4Hok8nGT15IHN64ZE-88-dlT3242341WD8RgPBg5zfIOQqAdgJlc-Aw", "has_more"=>true}

I tried using the below code and returned nil.

puts hash['profile']['team_member_id']

What is the recommended way to extract individual data from the above hash.

hash["members"] returns an array, so you would have to do:

hash["members"][0]["profile"]["team_member_id"]
hash["members"][0]["profile"]["name"]["display_name"]

You could also take advantage of the method called dig which works on both hash and array . The advantage with this one is that it returns nil if any key is not found:

hash.dig('members', 0, 'profile', 'team_member_id')
hash.dig('members', 0, 'profile', 'name', 'display_name')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM