gpt4 book ai didi

ruby - 在 ruby​​ 中,如何声明 "static"函数变量的 C++ 等价物?

转载 作者:太空宇宙 更新时间:2023-11-03 16:34:57 26 4
gpt4 key购买 nike

我正在尝试将一个散列保留在一个函数的本地,该函数会记住函数调用之间的状态。但我不知道如何在没有闭包的情况下声明它(正如一些用户在类似主题中建议的那样)。

我对 C++ 的了解比 ruby​​ 更透彻,在 C++ 中,我通常会使用 static 局部变量,就像这里的第一个例子:http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx

我设法使用 defined? 函数在 ruby​​ 中破解了一些东西:

def func x
if not defined? @hash
@hash = Hash.new
end

if @hash[x]
puts 'spaghetti'
else
@hash[x] = true
puts x.to_s
end
end

func 1
func 1

这会打印以下内容,这正是我想要的。唯一的问题是 @hash 可以在该函数之外访问。

1
spaghetti

是否有任何“更干净”、更受欢迎的方式来声明具有这种行为的变量(没有工厂)?我打算创建两个或三个变量,如 @hash,所以我正在寻找一种更好的方式来简洁地表达这一点。

最佳答案

您正在做的事情在 Ruby 中很常见,但也很常见,您无需为此大惊小怪。所有 @ 类型的实例变量仅对该实例是本地的。请记住,“实例”通常指类的实例,但它也可以指类的实例。

您可以使用 @@ 从实例的上下文中引用类实例变量,但这在实践中往往会变得困惑。

您要做的是以下其中一项。

在方法调用之间持续存在的变量,但仅在单个对象实例的上下文中:

def func(x)
# Instance variables are always "defined" in the sense that
# they evaluate as nil by default. You won't get an error
# for referencing one without declaring it first like you do
# with regular variables.
@hash ||= { }

if @hash[x]
puts 'spaghetti'
else
@hash[x] = true
puts x.to_s
end
end

在方法调用之间持续存在的变量,但仅在所有 对象实例的上下文中:

def func(x)
# Instance variables are always "defined" in the sense that
# they evaluate as nil by default. You won't get an error
# for referencing one without declaring it first like you do
# with regular variables.
@@hash ||= { }

if @@hash[x]
puts 'spaghetti'
else
@@hash[x] = true
puts x.to_s
end
end

这通常通过将 @@hash 包装到类方法中来变得更清晰。这具有使测试更容易的次要效果:

def self.func_hash
@func_hash ||= { }
end

def func(x)
if self.class.func_hash[x]
puts 'spaghetti'
else
self.class.func_hash[x] = true
puts x.to_s
end
end

关于ruby - 在 ruby​​ 中,如何声明 "static"函数变量的 C++ 等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9238142/

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