1

我们制作了以下代码并尝试运行它。

class Numeric
def gram 
self
end
alias_method :grams, :gram

def of(name)
    ingredient = Ingredient.new(name)
    ingredient.quantity=self
    return ingredient
  end
end


class Ingredient 
      def initialize(n)
        @@name= n
        end

      def quantity=(o)
      @@quantity = o
       return @@quantity
     end

     def name
       return @@name
     end

     def quantity
       return @@quantity
     end

   end

e= 42.grams.of("Test")
a= Ingredient.new("Testjio")
puts e.quantity
a.quantity=90
puts a.quantity
puts e.quantity

我们面临的问题是

puts a.quantity
puts e.quantity

即使对象不同,也是一样的。我们观察到的是第二个对象,即“a”正在替换第一个对象的值,即“e”。输出结果是

42
90
90

但所需的输出是

42
90
42

谁能建议为什么会这样?它不会替换对象,因为对象 ID 不同..只有对象的值被替换。

4

1 回答 1

3

问题是您使用的是类变量@@quantity而不是实例变量@quantity。只有一个class Ingredient,因此该变量在实例之间共享。只需删除额外的 @ 符号,它的行为就会如您所愿;@quantity每个实例都有一个Ingredient.

请参阅http://www.techotopia.com/index.php/Ruby_Variable_Scope#Ruby_Class_Variables

编辑:这是一个更简洁的成分版本,可以节省您编写访问器的时间。

class Ingredient
  attr_accessor :quantity, :name

  def initialize(n)
    @name = n
  end
end
于 2010-05-28T05:41:47.213 回答