在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'。只是一個偏好問題。 –