如何检查对象的ID是否存在于数组中?

时间:2013-01-01 01:20:07

标签: ruby arrays ruby-on-rails-3 logic

这是我正在尝试编写的逻辑,但我无法找到适当的Ruby方式来表达它:

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

基本上,如果id出现在特定数组的某个地方,我想返回true。

2 个答案:

答案 0 :(得分:4)

我认为您正在寻找Array#include?

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

希望有所帮助!

答案 1 :(得分:3)

使用Array #include?

实现此目的的一种方法是使用Array#include?方法转换逻辑并查询数组,而不是实例对象。例如:

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

这将返回一个布尔值,您可以将其插入到分支逻辑中。