Ruby - an alternative style to determine if an object is included in the list?

Let's say you have conditions with multiple ORs, for example.

if action == 'new' || action == 'edit' || action == 'update'

Another way to write this:

if ['new', 'edit', 'action'].include?(action)

but it seems like a “reverse” way of writing logic.

Is there a built-in way to do something like:

if action.equals_any_of?('new', 'edit', 'action')

?

Update - I am very addicted to this small snippet:

class Object
  def is_included_in?(a)
    a.include?(self)
  end
end

Update 2 - improvements based on the comments below:

class Object
  def in?(*obj)
    obj.flatten.include?(self)
  end
end
+3
source share
3 answers

Use regex?

action =~ /new|edit|action/

Or:

action.match /new|edit|action/

Or simply write a simple utility method that is semantically significant in the context of your application.

+5
source

Another way:

case action
when 'new', 'edit', 'action'
  #whatever
end

You can also use regex for this case.

if action =~ /new|edit|action/
+5
source

You can use notation %wfor string arrays:

%w(new edit action).include? action
+1
source

All Articles