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.

\$\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.

\$\endgroup\$
1
  • \$\begingroup\$ Are you the lifter or the liftee? \$\endgroup\$ 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

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.