2

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

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

5 Comments

@PaulRichter: find is another alias.
I try to avoid find only because in Rails, on AR objects, find is really different than detect. So to keep things clear (for me), I try to use find when it's an AR#find and detect when it's an Enumerable. Just a matter of preference.
It does appear that detect and find are the same thing. Anyone know the reason for the different names (assuming there is no practical difference, other than the preferential reason mr rogers mentioned)?
@PaulRichter: Best I'm aware the aliases are nothing more than a reflection of Matz's views on what is natural: en.wikipedia.org/wiki/Ruby_(programming_language)#Philosophy
2

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.