在Ruby中,我有一个如下所示的哈希。如何获得tag_type为“LocationTag”的“tag”的“名称”?在这种情况下,返回的值将是“新加坡”。在Ruby中过滤数组
是最好的方法,只是做:
location = nil
tags.each do |t|
if t["tag_type"] == "LocationTag"
location = t.name
end
end
或根本红宝石有过滤哈希一个更好的方法?
{
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"
}
]
}
[直接链接到'detect'方法(HTTP:// ruby-doc.org/core-2.2.0/Enumerable.html#method-i-detect) –
@PaulRichter:'find'是另一个别名。 –
我试图避免'find',因为在Rails中,在AR对象上,'find'与'detect'真的不同。所以为了保持清楚(对我来说),我试着在'AR#find'时使用'find',在Enumerable时使用'detect'。只是一个偏好问题。 –