Rok
Rok

Reputation: 227

ruby hash check if value exists

Must be an easy question.. but I can't seem to find the answer. I'm trying to check if a value exists for a specific key within hash.

hash = {{"name" => "John", "Loc" => "US", "fname" => "John Doe"},
        {"name" => "Eve", "Loc" => "UK", "fname" => "John Eve"}}

Currently I am looping through hash, to check for if h["name"] = "John"...

I was looking to see if a .include or .has_value? type of approach is available. I read the documentation on hash and a book I have on hand but couldn't find it.

I thought something like if hash["name"].has_value?("John") be most useful than looping through hash. Thanks in advance for the help!

Upvotes: 2

Views: 8125

Answers (1)

spickermann
spickermann

Reputation: 106882

First of all our hash is not a valid hash. I suppose you want to have an array of hashes like this

array = [
  { "name" => "John", "Loc" => "US", "fname" => "John Doe" },
  { "name" => "Eve",  "Loc" => "UK", "fname" => "John Eve" }
]

then you can do something like this:

array.select { |hash| hash['name'] == 'John' }
# => returns [{"name" => "John", "Loc" => "US", "fname" => "John Doe"}] 

array.any? { |hash| hash['name'] == 'John' }
# => true

Upvotes: 7

Related Questions