【问题标题】:What is wrong with this Ruby code (I'm assuming it is in the if/else statement)?这段 Ruby 代码有什么问题(我假设它在 if/else 语句中)?
【发布时间】:2015-04-27 14:17:47
【问题描述】:

此代码的目标是,如果对象的item_nameqty 与被比较对象的相同,则使其返回true。使用我的代码,两者都返回 false。

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

【问题讨论】:

    标签: ruby object if-statement equality


    【解决方案1】:
    def ==(other_item)
      item_name == other_item.item_name && qty == other_item.qty
    end
    

    您正在检查当前项目的名称是否等于数量;这不太可能是真的。 (另外,鉴于您返回的是布尔值,if 是多余的。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      相关资源
      最近更新 更多