AdamNYC
AdamNYC

Reputation: 20415

How to check if object belongs to an array in Ruby

I usually have to check things like:

if ['Bob','Mary','John'].include? @user.name

Is there a way to write something like:

if @user.name.in? ['Bob','Mary','John']

Thank you.

Upvotes: 3

Views: 1846

Answers (2)

fl00r
fl00r

Reputation: 83680

Rails 3.1 has got this Object.in? method

characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true

character = "Konata"
character.in?("Konata", "Kagami", "Tsukasa") # => true

Upvotes: 6

phlogratos
phlogratos

Reputation: 13924

If @user.name is a String, you can add in? to String.

class String                                                                                                                                                          
  def in? a
    a.include? self
  end
end

This has the following effect:

irb(main):011:0> 'Bob'.in? ['Bob','Mary','John']
=> true
irb(main):012:0> 'Jane'.in? ['Bob','Mary','John']
=> false

Upvotes: 4

Related Questions