Martin Petrov
Martin Petrov

Reputation: 2643

Find if an array of objects includes an attribute with a specific value

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 %>

Upvotes: 21

Views: 21683

Answers (3)

Tamik Soziev
Tamik Soziev

Reputation: 14798

you can also use all? method:

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

Upvotes: 1

Jacob
Jacob

Reputation: 1536

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

Upvotes: 5

Mike Lewis
Mike Lewis

Reputation: 64147

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

Using the any? method

Upvotes: 34

Related Questions