d_zero d_zero - 4 months ago 9
Ruby Question

Finding an element in an array inside a hash

@members = {
approved: ["Jill"],
unapproved: ["Daniel"],
removed: ["John"],
banned: ["Daniel", "Jane""]
}


Very simply: making a program to track membership. In the above hash you can see the four membership status keys each with an array containing names.

I'm trying to create a find_member method which allows the user to enter a name and then searches each array for the name and tells the user which key the name was found in.

I'm not very good with hashes and in attempting to do this I've created a mess of loops and I imagine there's a very easy solution, I just haven't found it so far. Is there a really simple way to do this?

I've tried a few things and don't have all my past efforts still, but this is the latest mess I've ended up with, which is probably worse than what I had previously:

def find_member
puts "==Find Member=="
puts "Name: "
@name = gets.chomp
@members.each do |key|
key.values.each do |array|
array.each do |element|
if @name == element
puts "#{@name} found in #{key}"
else
puts "#{@name} not found in #{key}"
end
end
end
end
end
end


Thanks.

Answer

You can use this itteration with include? method.

@members = {
  approved: ["Jill"],
  unapproved: ["Daniel"],
  removed: ["John"],
  banned: ["Daniel", "Jane"]
}

def find_member_group(name)
  @members.each { |group, names| return group if names.include?(name) }
  nil
end

@name = 'Jane'

group_name = find_member_group(@name)
puts group_name ? "#{@name} found in #{group_name}." : "#{@name} not found."
# => Jane found in banned.