a = [4, 3, 2, nil]
a.max_by { |v| v * 2 } => NoMethodError: undefined method `*' for nil:NilClass
How to overload max_by to ignore nil values?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Welcome to Ruby: there are so many ways to solve the problem!
A very simple solution is:
since nil coerces to float as 0. This doesn’t handle negative values, but since nil is only a single instance of a class called NilClass, now as with all classes in Ruby we can open it an let it learn a littly maths:
now we have
returning 4.