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.)
    – antinome
    Commented Mar 20, 2013 at 16:04

3 Answers 3

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

Using the any? method

0
5

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

1

you can also use all? method:

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

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.