开发者

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

开发者 https://www.devze.com 2023-02-18 07:08 出处:网络
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 objec开发者_开发问答t which attribute \'hidd

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 objec开发者_开发问答t which attribute 'hidden' has "false' value:

<% if positions.collect{|position| position.hidden}.include?(false) %>
  ...
<% end %>


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

Using the any? method


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


you can also use all? method:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号