我们制作了以下代码并尝试运行它。
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 不同..只有对象的值被替换。