Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find key of value within array in hash

Tags:

ruby

hash

I have a hash categories as following:

categories = {"horeca" => ["bar", "waiter", "kitchen"], 
              "retail" => ["eerste", "tweede"]}

I want to find they key if the value is included in the array of values.

Something like following

categories.key("bar")

which would return "horeca"

as of now I can only get "horeca" if I do

categories.key(["bar", "waiter", "kitchen"])
like image 302
Martijn Kerckhaert Avatar asked Dec 03 '22 12:12

Martijn Kerckhaert


1 Answers

Try Enumberable#find:

categories.find { |key, values|
  values.include?("bar")
}.first
like image 164
Mate Solymosi Avatar answered Dec 21 '22 22:12

Mate Solymosi