gpt4 book ai didi

ruby - 为什么我不能在我声明的地方创建我的私有(private)变量?

转载 作者:数据小太阳 更新时间:2023-10-29 07:46:54 24 4
gpt4 key购买 nike

考虑以下代码

class CheckOut 
@rules
@total = 0
@basket = Hash.new

def initialize(rules, discounts)
@total=0
#if i use the line below everything is ok.
#@basket = Hash.new
@rules = rules
end

def scan sku
price = @rules[sku]
if @basket.has_key?(sku) #I get NoMethodError: undefined method `has_key?' for nil:NilClass
@basket[sku] += 1
else
@basket[sku] = 1
end
@total += price
end

def total
@total
end
end

如果我按原样运行代码,我会在 has_key 上得到一个 noMethodError?但是如果我在初始化中创建哈希,一切正常。为什么我不能在声明中创建哈希?

最佳答案

当你在类体中定义一个实例变量时,它是一个定义在 CheckOut 上的类实例变量,它是 Class 的一个实例,并且不存在于 CheckOut 的实例中。相反,您需要在 initialize 中定义实例变量(因为 initialize 在新的 CheckOut 实例的上下文中运行) :

class CheckOut
def initialize(rules, discounts)
@total = 0
@basket = Hash.new
@rules = rules
end
...
end

下面是一个进一步说明这一点的简单示例:

class Foo
@bar = "class bar!"
@baz = "class baz!"
def initialize
@bar = "instance bar!"
end
end

Foo.instance_variable_get(:@bar) #=> "class bar!"
Foo.new.instance_variable_get(:@bar) #=> "instance bar!"

Foo.instance_variable_get(:@baz) #=> "class baz!"
Foo.new.instance_variable_get(:@baz) #=> nil

这也表明所有 实例变量默认为nil,即使它们以前从未被引用过。这就是为什么您的错误是 NoMethodError for nil:NilClass 而不是 NameError

关于ruby - 为什么我不能在我声明的地方创建我的私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10376440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com