21

The following code works, but can you tell me if this is the right way to do it?

I have an array of Position objects and I want to check if it contains an object which attribute 'hidden' has "false' value:

<% if positions.collect{|position| position.hidden}.include?(false) %>
  ...
<% end %>
1
  • 2
    If you like, another way to simplify this is: if positions.map(&:hidden).include?(false). (Warning: this and the original approach will behave differently from the answers given below if the 'hidden' attribute ever returns nil.) Commented Mar 20, 2013 at 16:04

3 Answers 3

34
<% if positions.any?{|position| !position.hidden} %>
  ...
<% end %>

Using the any? method

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

Comments

5

if positions.any? {|position| not position.hidden}

Comments

1

you can also use all? method:

<% unless positions.all? {|position| position.hidden} %>
 ...
<% end %>

Comments

Your Answer

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.