jwilsco
jwilsco

Reputation: 408

How do I check whether an object's ID is present in an array?

Here's the logic I'm trying to write, but I can't find the proper Ruby way to say it:

if Object.id [occurs in this array ->] [13, 16, 234]
   #run this code if true
else
   #run this code if false
end

Basically I want to return true if an id occurs somewhere in a specific array.

Upvotes: 0

Views: 76

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84453

Use Array#include?

One way to do this is to turn the logic around and query the array, rather the instance object, for inclusion using the Array#include? method. For example:

[13, 16, 234].include? my_object.id

This will return a boolean value, which you can plug into your branching logic.

Upvotes: 3

Xavier Holt
Xavier Holt

Reputation: 14619

I think you're looking for Array#include?:

if [13, 16, 234].include? Object.id
    #run this code if true
else
    #run this code if false
end

Hope that helps!

Upvotes: 4

Related Questions