我试图通过重写抽屉类中的方法“remove_item”来删除@contents数组中的Silverware类。此方法应该采用银器的@type名称的参数。
class Drawer
attr_reader :contents
def initialize
@contents = []
end
def add_item(item)
@contents << item
end
def remove_item(item = @contents.pop)
@contents.delete(item) # I have to fix this.
end
end
class Silverware
attr_reader :type
def initialize(type, clean = true)
@type = type
end
end
silverware_drawer = Drawer.new # creating new drawer
silverware_drawer.add_item(Silverware.new("spoon")) # adding silverware
p silverware_drawer.contents # I get this >> [#<Silverware:0x007f84aa091ad8 @type="spoon", @clean=true>]
p silverware_drawer.remove_item("spoon") # removing spoon
p silverware_drawer.contents # Show drawer and I still get [#<Silverware:0x007f84aa091ad8 @type="spoon", @clean=true>]
任何帮助将不胜感激!提前谢谢!
答案 0 :(得分:1)
你没有传入对象。你只是传递了这种类型。所以你必须找到类型&#34;勺子&#34;并从数组中删除它
def remove_item(item)
@contents.delete(@contents.find{|content| content.type == item})
end