How to Find a Hash Key Containing a Matching Value

How to find a hash key containing a matching value

You could use Enumerable#select:

clients.select{|key, hash| hash["client_id"] == "2180" }
#=> [["orange", {"client_id"=>"2180"}]]

Note that the result will be an array of all the matching values, where each is an array of the key and value.

How to find a hash key containing a matching value for a hash having array of values

res = []
client.each{|k, v|
res << k if v.detect{|hash| hash["client_id"] == "2282"}
}
res
#=> ["red", "yellow"]

NOTE
This answer is for OPs original question that required finding keys that contained "client_id" = 2282. I have not updated my answer as OP changed the requirement quite lazily.

How do you check for matching keys in a ruby hash?

I think you could replace those for loops with the Array#each. But in your case, as you're creating a hash with the values in people_list, then you could use the Enumerable#each_with_object assigning a new Hash as its object argument, this way you have your own person hash from the people_list and also a new "empty" hash to start filling as you need.

To check if your inner hash has a key with the value person[:favourites][:tv_show] you can check for its value just as a boolean one, the comparison with false can be skipped, the value will be evaluated as false or true by your if statement.

You can create the variables tv_show and name to reduce a little bit the code, and then over your tv_friends hash to select among its values the one that has a length greater than 1. As this will give you an array inside an array you can get from this the first element with first (or [0]).

def tv_show(people_list)
tv_friends = people_list.each_with_object(Hash.new({})) do |person, hash|
tv_show = person[:favourites][:tv_show]
name = person[:name]

hash.key?(tv_show) ? hash[tv_show] << name : hash[tv_show] = [name]
end
tv_friends.values.select { |value| value.length > 1 }.first
end

Also you can omit parentheses when the method call doesn't have arguments.

Find key of value within array in hash

Try Enumberable#find:

categories.find { |key, values|
values.include?("bar")
}.first

Find a value in a nested hash

Found a way to do it with nested maps, a compact and a flatten.first:

fnd="theFoo"
data.map{|t,th|th.map{|s,sh|sh.map{|f,fh|fh["id"]if fh["name"]==fnd}.compact}}.flatten.first

==> 1

Ruby group hashes based on matching keys and store the value of non matching keys in an array

You can try grouping by key and value and then map the revenue values:

foos
.group_by { |e| e.values_at(:key, :value) }
.map do |(key, value), values|
{ key: key, value: value, revenue: values.map { |e| e[:revenue] } }
end
# [{:key=>"Foo", :value=>1, :revenue=>[2, 4]}, {:key=>"Bar", :value=>2, :revenue=>[7]}, {:key=>"bar", :value=>2, :revenue=>[9]}, {:key=>"Zampa", :value=>4, :revenue=>[9]}]


Related Topics



Leave a reply



Submit