用Ruby过滤数组

用Ruby过滤数组,ruby,Ruby,在Ruby中,我有一个如下所示的散列。如果标签类型为“LocationTag”,如何获取“标签”的“名称”?在这种情况下,返回的值将是“singapore” 最好的方法是: location = nil tags.each do |t| if t["tag_type"] == "LocationTag" location = t.name end end 或者ruby有更好的过滤散列的方法吗 { tags: [ { "id

在Ruby中,我有一个如下所示的散列。如果标签类型为“LocationTag”,如何获取“标签”的“名称”?在这种情况下,返回的值将是“singapore”

最好的方法是:

location = nil
tags.each do |t|
  if t["tag_type"] == "LocationTag" 
    location = t.name
  end
end
或者ruby有更好的过滤散列的方法吗

   {
      tags: [
        {
          "id": 81410,
          "tag_type": "SkillTag",
          "name": "angular.js",
          "display_name": "Angular.JS",
          "angellist_url": "https:\/\/angel.co\/angular-js"
        },
        {
          "id": 84038,
          "tag_type": "SkillTag",
          "name": "bootstrap",
          "display_name": "Bootstrap",
          "angellist_url": "https:\/\/angel.co\/bootstrap"
        },
        {
          "id": 1682,
          "tag_type": "LocationTag",
          "name": "singapore",
          "display_name": "Singapore",
          "angellist_url": "https:\/\/angel.co\/singapore"
        },
        {
          "id": 14726,
          "tag_type": "RoleTag",
          "name": "developer",
          "display_name": "Developer",
          "angellist_url": "https:\/\/angel.co\/developer"
        }
    ]
 }
找到结果后,可以使用停止迭代:

location = tags.find { |t| t["name"] if t["tag_type"] == "LocationTag" }

请注意上面修复的错误:
t.name
=“LocationTag”

这将让您获得第一个点击:

tags.detect{|tag| tag['tag_type'] == 'LocationTag'}['name']
这将作为一个数组提供所有命中率

tags.select{|tag| tag['tag_type'] == 'LocationTag'}.map{|t| t['name']}
查看文档以了解更多详细信息


(感谢@PaulRichter的评论……这是对文章的一个很好的澄清补充)

@PaulRichter:
find
是另一个别名。我尽量避免
find
,只是因为在Rails中,在AR对象上,
find
detect
确实不同。因此,为了保持清楚(对我来说),我尝试在
AR时使用
find
,在
可枚举时使用
detect
。只是偏好的问题。
detect
find
似乎是一回事。有人知道不同名字的原因吗(假设没有实际的区别,除了罗杰斯先生提到的优先原因外)?@PaulRichter:我所知道的最好的情况是,这些别名只不过是Matz对什么是自然的看法的反映: