4

我有一个像你在这篇文章底部看到的那样的数组(具体来说,它是从 fb_graph 返回的 fb 好友列表)。

如果我想通过这个哈希并从每条记录中挑选出“标识符”属性,我知道我可以做这样的事情:

@fb_friends.map &:identifier  # returns ["123", "134",...]

我的问题是,如果我想从每条记录中挑选出多个属性怎么办。基本上我想获取标识符、名称和图片。我天真地想做类似的事情:

@fb_friends.map &:identifier, :name, :picture

但这当然行不通。知道我该怎么做吗?

[#<FbGraph::User:0x007f9ec1fd63c8 @identifier="1868", @endpoint="https://graph.facebook.com /----",  @access_token="AAAFGzU8vU0gBAEK2q3WYEUJNZAczuO6UPOLqbscwvZALr1gW1ePBqpyarh0uTv6alA2YyNvIzZBcvvIBEYy4i5ulMJZCpWcZD", @cached_collections={}, @name="REMOVED", @first_name=nil, @middle_name=nil, @last_name=nil, @gender=nil, @locale=nil, @languages=[], @link=nil, @username=nil, @third_party_id=nil, @timezone=nil, @verified=nil, @about=nil, @bio=nil, @education=[], @email=nil, @interested_in=[], @political=nil, @favorite_teams=[], @quotes=nil, @relationship_status=nil, @religion=nil, @relationship=nil, @website=nil, @work=[], @sports=[], @favorite_athletes=[], @inspirational_people=[], @mobile_phone=nil, @installed=nil>, #<FbGraph::User:0x007f9ec1fda9f0 @identifier="3??1", @endpoint="https://graph.facebook.com/----", @access_token="AAAFGzU8vU0gBAEK2q3WYEUJNZAczuO6UPOLqbscwvZALr1gW1ePBqpyarh0uTv6alA2YyNvIzZBcvvIBEYy4i5ulMJZCpWcZD", @cached_collections={}, @name="Removed", @first_name=nil, @middle_name=nil, @last_name=nil, @gender=nil, @locale=nil, @languages=[], @link=nil, @username=nil, @third_party_id=nil, @timezone=nil, @verified=nil, @about=nil, @bio=nil, @education=[], @email=nil, @interested_in=[], @political=nil, @favorite_teams=[], @quotes=nil, @relationship_status=nil, @religion=nil, @relationship=nil, @website=nil, @work=[], @sports=[], @favorite_athletes=[], @inspirational_people=[], @mobile_phone=nil, @installed=nil>, #<FbGraph::User:0x007f9ec1fe5030
4

2 回答 2

11

这看起来不像嵌套哈希。它看起来像一个 FbGraph::User 实例数组。如果你想把它变成一个哈希数组,每个都包含 :identifier、:name 和 :picture,你可以这样做:

@fb_friends.map { |f|
  { identifier: f.identifier, name: f.name, picture: f.picture }
}
于 2012-07-11T00:53:27.813 回答
1

IIRC 这将返回一个哈希数组,其中键是 id,值是带有名称和图片的数组:

@fb_friends.map{|fbf| [fbf.identifier, [fbf.name, fbf.picture]]}.map{|a| Hash[a]}

{:id1 => ['name', 'picture_url'], :id2 => ['name2', 'picture_url2]}
于 2012-07-11T00:54:12.553 回答