# Return nil after loop and also in unless block in Ruby

I have a working code as below. Is there any better way to return nil after the each loop and unless else in the below example?

def find_member(member_name)
unless members.empty?
members.each do |member|
if member.name == member_name
return member
end
end
nil
else
nil
end
end


I should pass nil in each case because there are different conditions in other methods where this method is called. That is the reason why I have written the code as above.

Ruby has a detect method, so your entire method can be replaced with
members.detect { |member| member.name == member_name }

As an aside, each works fine for empty arrays, hence the empty? check you have is completely unnecessary even if you keep the explicit loop.
It's a method on Enumerable. It is also aliased to find which may be a more descriptive verb depending on the context. Using the built-in functions will always be faster because they are implemented in c