Don P
Don P

Reputation: 63567

Filter an array in Ruby

In Ruby, I have a hash like below. How can I get the "name" of the "tag" where the tag_type is "LocationTag"? In this case, the returned value would be 'singapore'.

Is the best method just to do:

location = nil
tags.each do |t|
  if t["tag_type"] == "LocationTag" 
    location = t.name
  end
end

or does ruby have a better method for filtering hashes?

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

Upvotes: 2

Views: 489

Answers (2)

Denis de Bernardy
Denis de Bernardy

Reputation: 78423

You can use find to stop the iteration once you've found a result:

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

Mind the errors that got fixed in the above: t.name and = "LocationTag".

Upvotes: 2

mr rogers
mr rogers

Reputation: 3260

This will get you the first hit:

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

This will give you all hits as an array

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

Check out the docs for Ruby#Enumerable for more details.

Ruby#Enumerable:detect

Ruby#Enumerable:select

(Thanks @PaulRichter for the comment... it's a nice clarifying addition to the post)

Upvotes: 3

Related Questions