提问人:Monkey Em585 提问时间:4/27/2015 更新时间:4/27/2015 访问量:58
这个 Ruby 代码有什么问题(我假设它在 if/else 语句中)?
What is wrong with this Ruby code (I'm assuming it is in the if/else statement)?
问:
此代码的目标是,如果对象的 和 与被比较对象的 和相同,则返回 true。使用我的代码,两者都返回 false。item_name
qty
class Item
attr_reader :item_name, :qty
def initialize(item_name, qty)
@item_name = item_name
@qty = qty
end
def to_s
"Item (#{@item_name}, #{@qty})"
end
def ==(other_item)
if @item_name.==(@qty)
true
else
false
end
end
end
p Item.new("abcd",1) == Item.new("abcd",1)
p Item.new("abcd",2) == Item.new("abcd",1)
我应该怎么做才能解决它?我还尝试让 if/else 语句说以下内容:
1.
if @item_name == @qty
true
else
false
end
2.
if item_name == qty
true
else
false
end
3.
if item_name.==(qty)
true
else
false
end
答:
2赞
Amadan
4/27/2015
#1
def ==(other_item)
item_name == other_item.item_name && qty == other_item.qty
end
您正在检查当前项目的名称是否等于数量;这不太可能是真的。(此外,鉴于您返回的是布尔值,因此 an 是多余的。if
评论