Ruby - 用于确定对象是否包含在列表中的替代样式?

And*_*ite 3 ruby

假设您有多个OR的条件,例如

if action == 'new' || action == 'edit' || action == 'update'
Run Code Online (Sandbox Code Playgroud)

另一种写这个的方法是:

if ['new', 'edit', 'action'].include?(action)
Run Code Online (Sandbox Code Playgroud)

但这感觉就像编写逻辑的"向后"方式.

是否有任何内置方式可以执行以下操作:

if action.equals_any_of?('new', 'edit', 'action')
Run Code Online (Sandbox Code Playgroud)

更新 - 我非常热衷于这个小片段:

class Object
  def is_included_in?(a)
    a.include?(self)
  end
end
Run Code Online (Sandbox Code Playgroud)

更新2 - 基于以下评论的改进:

class Object
  def in?(*obj)
    obj.flatten.include?(self)
  end
end
Run Code Online (Sandbox Code Playgroud)

Dav*_*ton 5

使用正则表达式?

action =~ /new|edit|action/
Run Code Online (Sandbox Code Playgroud)

要么:

action.match /new|edit|action/
Run Code Online (Sandbox Code Playgroud)

或者只是编写一个在应用程序上下文中具有语义意义的简单实用程序方法.


edg*_*ner 5

还有另一种方式

case action
when 'new', 'edit', 'action'
  #whatever
end
Run Code Online (Sandbox Code Playgroud)

对于这样的情况,您也可以使用正则表达式

if action =~ /new|edit|action/
Run Code Online (Sandbox Code Playgroud)