Check if any of multiple conditions are true in Ruby

落爺英雄遲暮 提交于 2020-01-17 07:28:28

问题


I have the following Ruby conditional:

<% if can? :read, %w(policy journey crash user).map(&:to_sym) %>

Which I want to translate to: if the user has read permissions for any of the resources in the array.

However it always returns false. How can I fix it?

I don't want to do:

if can? :read, :policy || can? :read, :journey || etc...

回答1:


Sure you can.

Enumerable#any? is exactly what you're looking for:

<% if %i(policy journey crash user).any? { |action| can? :read, action } %>

The above will return true only if can read any action.

Note, I used %i instead of %w. It gives you array of symbols.



来源:https://stackoverflow.com/questions/42655504/check-if-any-of-multiple-conditions-are-true-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!