如何检查我的数组是否包含对象? [英] How do I check to see if my array includes an object?

查看:43
本文介绍了如何检查我的数组是否包含对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组 @horses = [],我用一些随机的马填充.

I have an array @horses = [] that I fill with some random horses.

如何检查我的 @horses 数组是否包含已包含(存在)的马?

How can I check if my @horses array includes a horse that is already included (exists) in it?

我尝试了类似的东西:

@suggested_horses = []
  @suggested_horses << Horse.find(:first,:offset=>rand(Horse.count))
  while @suggested_horses.length < 8
    horse = Horse.find(:first,:offset=>rand(Horse.count))
    unless @suggested_horses.exists?(horse.id)
       @suggested_horses<< horse
    end
  end

我也尝试过 include? 但我看到它仅用于字符串.使用 exists? 我收到以下错误:

I also tried with include? but I saw it was for strings only. With exists? I get the following error:

undefined method `exists?' for #<Array:0xc11c0b8>

所以问题是如何检查我的阵列是否已经包含一匹马",以便我不会用同一匹马填充它?

So the question is how can I check if my array already has a "horse" included so that I don't fill it with the same horse?

推荐答案

Ruby 中的数组没有 exists? 方法,但它们有一个 include? 方法 如文档中所述.类似的东西

Arrays in Ruby don't have exists? method, but they have an include? method as described in the docs. Something like

unless @suggested_horses.include?(horse)
   @suggested_horses << horse
end

应该是开箱即用的.

这篇关于如何检查我的数组是否包含对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆