1
\$\begingroup\$

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.

asked Aug 17, 2020 at 17:28
\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

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.

answered Aug 17, 2020 at 20:05
\$\endgroup\$
1
  • \$\begingroup\$ Are you the lifter or the liftee? \$\endgroup\$ Commented Feb 4, 2021 at 18:51
-1
\$\begingroup\$

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

answered Aug 29, 2020 at 22:21
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.