ruby - 为什么我的 ruby​​ 方法总是返回 true?

标签 ruby class collections boolean

从 codeschool 的 ruby​​-bits 类(class)中,我试图了解这些类是如何工作的——我有一个 Game 类和一个名为 Library 的集合类,它存储了一个集合游戏。

class Game
  attr_accessor :name, :year, :system
  attr_reader :created_at

  def initialize(name, options={})
    self.name = name
    self.year = options[:year]
    self.system = options[:system]
    @created_at = Time.now
  end


  def ==(game)
    name == game.name && 
    system == game.system &&
    year == game.year
  end
end

库类:

class Library
  attr_accessor :games

  def initialize(*games)
    self.games = games
  end

  def has_game?(*games)
    for game in self.games
      return true if game == game
    end
    false
  end
end

现在我创建了一些游戏:

contra = Game.new('Contra', {
  year: 1994,
  system: 'nintendo'
})

mario = Game.new('Mario', {
  year: 1996,
  system: 'SNES'
})

sonic = Game.new('Sonic', {
  year: 1993,
  system: 'SEGA'
})

并实例化一个新集合:

myCollection = Library.new(mario, sonic)

当我尝试使用 has_game? 方法查找某个游戏是否在 myCollection 中时,我总是得到 true

puts myCollection.has_game?(contra) #=> 返回 **true** 即使它从未作为集合的一部分插入。

我做错了什么?

最佳答案

return true if game == game

我认为这种说法可能会引起问题。

它总是正确的。

你可能想要这样的东西:

def has_game?(wanted)
  for game in self.games
    return true if game == wanted
  end
  false
end

关于ruby - 为什么我的 ruby​​ 方法总是返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13936891/

相关文章:

ruby - 是什么启发了 Ruby 的 =begin .. =end 注释 block 语法?

ruby-on-rails - Rails Engine 内部的公寓 gem 迁移

ruby - 主环境`return`

java - 为什么 List 不简单地定义为抽象类而不是接口(interface)?

java - 在 Java 中从 Map 分离 Collection 的最佳方法是什么?

ruby-on-rails - 在 rails 控制台中删除所有内容

python - 将元素 append 到 Python 中的空列表字典

wpf - 将 ComboBox 绑定(bind)到嵌套在类中的枚举

c# - Web 服务创建实例问题 -> 找不到引用契约(Contract) 'MyWebService.ClassName' 的默认端点元素

Java:用于保存不同类型基元的通用集合