从 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/