2014-12-26 50 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"