2

Hi I want to have a condition, which when it is nil, it true, or it call check method and return true/false. For example:

(apple.nil? || apple.sweet?) && (pear.nil? || pear.sweet?) 

It checks if all the fruits are sweet(only apple&pear here). Is there any ruby idiom to simplify this code?

Cheers

2 Answers 2

6

if all the fruits are sweet

[apple, pear].compact.all?(&:sweet?) 

compact gets rid of the nil elements, then all?(&:sweet?) checks if all remaining ones are sweet.

Sign up to request clarification or add additional context in comments.

1 Comment

Even works for the edge case of an empty array: all? returns true in that case.
4

An alternative to the solution given by Amadan:

fruits.all? { |f| f.nil? || f.sweet? } 

While the idea of using compact, as Amadan correctly suggested, is nice and concise, it will likely create a temporary array of the non-nil elements, while just using all? does not need such an array, and iteration stops as soon an element has been encountered which does not fulfil the condition.

Of course if you only have exactly two fruits in your code, which are mentioned expcitly, I would consider your code better to understand than doing a

[apple,pear].all? {...} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.