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.
2 Answers 2
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.
-
\$\begingroup\$ Are you the lifter or the liftee? \$\endgroup\$Cary Swoveland– Cary Swoveland2021年02月04日 18:51:33 +00:00Commented Feb 4, 2021 at 18:51
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