2014-12-26 108 views
2

在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" 
     } 
    ] 
} 

回答

3

這將讓你先打:

tags.detect{|tag| tag['tag_type'] == 'LocationTag'}['name'] 

這會給你所有的命中作爲一個數組

tags.select{|tag| tag['tag_type'] == 'LocationTag'}.map{|t| t['name']} 

檢查出Ruby#Enumerable的文檔瞭解更多詳情。

Ruby#Enumerable:detect

Ruby#Enumerable:select

(感謝@PaulRichter的評論...這是一個很好的澄清除後)

+1

[直接鏈接到'detect'方法(HTTP:// ruby-doc.org/core-2.2.0/Enumerable.html#method-i-detect) –

+1

@PaulRichter:'find'是另一個別名。 –

+1

我試圖避免'find',因爲在Rails中,在AR對象上,'find'與'detect'真的不同。所以爲了保持清楚(對我來說),我試着在'AR#find'時使用'find',在Enumerable時使用'detect'。只是一個偏好問題。 –

2

您可以使用find停止迭代一旦你找到了一個結果:

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

記住,得到固定在上面的錯誤:t.name= "LocationTag"