开发者

How do I fetch multiple hash keys with a nested hash?

I'm playing around with nested hashes and I'm trying to figure out how to fetch multiple keys when my hash is a nested one:

imahash = { :id => { :name => "Alma", :email => "alma@mail.com" },
   开发者_如何学Go         :stats => { :gender => "Female" }, 
            :location => { :city => "Freeport", :state => "Maine" } 
          }

I know how to retrieve the nested value, and typing in the hash name will dump all the keys and values. But what I want to do is to fetch specific keys, such as :name and :gender only. Or :name and :city only.

Is this possible? Because from what I've found, it seems that you can only retrieve hash values for one key at a time or for all the keys at once.

My desired output would be something like:

=> { :id => { :name => "Alma" }, :location => { :city => "Freeport" } }


I presume you want to grab the values out in a tuple? You can make an array that contains whatever collection of values you want.

Try the following for name and city:

[imahash[:id][:name], imahash[:location][:city]]
=> ["Alma", "Freeport"]


Not exactly sure what you're asking here, but it seems like you're wanting to create a new hash from the bigger one.

To fetch specific keys like :name and :gender only

name_and_gender_hash = {
  :name   => imahash[:id][:name],
  :gender => imahash[:stats][:gender]
}

would result in

{:name => "Alma", :gender => "female"}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜