【问题标题】:Check if any of multiple conditions are true in Ruby检查Ruby中的多个条件中的任何一个是否为真
【发布时间】:2017-03-07 18:20:37
【问题描述】:

我有以下 Ruby 条件:

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

我要翻译为:如果用户对数组中的任何资源具有读取权限。

但是它总是返回 false。我该如何解决?

我不想做:

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

【问题讨论】:

  • 在不知道can? 方法长什么样的情况下,我认为我们无法回答您...
  • %w(policy journey crash user).map(&amp;:to_sym) 在较新的红宝石中会比 %i(policy journey crash user) 更好。
  • @muistooshort 我正在使用%w...
  • %w(...) 生成一个字符串数组,然后将其转换为符号,%i(...) 直接生成一个符号数组。

标签: ruby cancan cancancan


【解决方案1】:

当然可以。

Enumerable#any? 正是您要找的:

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

仅当can read any action 时,上述内容才会返回true

注意,我使用了%i 而不是%w。它为您提供符号数组。

【讨论】:

  • 看起来 OP 想看到 any? 而不是 all?,但不想写 can? :read, :policy || can? :read, :journey || etc...,因为它不是 DRY。
猜你喜欢
  • 2012-01-11
  • 2017-07-16
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 2022-12-09
  • 2018-07-02
  • 2019-04-07
  • 1970-01-01
相关资源
最近更新 更多