在 ruby 中,如何声明 C++相当于“静态”。函数变量?
我试图将哈希保留在一个函数的本地,该函数会记住该函数调用之间的状态。但我不知道如何在没有闭包的情况下声明它(正如一些用户在类似线程中建议的那样)。
我比 ruby 更了解 C++,在 C++ 中,我通常会使用 static
局部变量,就像这里的第一个示例:http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx
我设法破解了一些东西在 ruby 中使用 define?
函数一起:
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
,因此我正在寻找一种更好的方法来简洁地表达这一点。
I'm trying to keep a hash local to one function that remembers its state between calls to the function. But I don't know how to declare it without a closure (as some users suggested in a similar thread).
I know C++ more thoroughly than ruby, and in C++, I would have ordinarily used a static
local variable, like in the first example here: http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx
I managed to hack something together in ruby using the defined?
function:
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
This prints, the following, which is kind of what I want. The only problem is that @hash
can be accessed outside of that function.
1
spaghetti
Is there any "cleaner", more preferred way to declare a variable with this behavior (without a factory)? I was going to create two or three variables like @hash
, so I was looking for a better way to express this concisely.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所做的事情在 Ruby 中很常见,但也很常见,因此您无需对此大惊小怪。所有
@
类型的实例变量仅是该实例的本地变量。请记住,“实例”通常指类的实例,但它也可以指类的实例。您可以使用
@@
从实例的上下文中引用类实例变量,但这在实践中往往会变得混乱。您想做的是以下操作之一。
在方法调用之间持续存在的变量,但仅在单个对象实例的上下文中:
在方法调用之间持续存在的变量,但仅在所有对象实例的上下文中:
通常通过将
@@hash
包装到类方法中来使这更清晰。这具有使测试更容易的次要效果:What you're doing is pretty common in Ruby, but also so common you don't need to make a big fuss about it. All
@
-type instance variables are local to that instance only. Keep in mind "instance" generally refers to an instance of a class, but it can refer to the instance of the class as well.You can use
@@
to refer to a class instance variable from the context of an instance, but this tends to get messy in practice.What you want to do is one of the following.
A variable that persists between method calls, but only within the context of a single object instance:
A variable that persists between method calls, but only within the context of all object instances:
This is usually made cleaner by wrapping the
@@hash
into a class method. This has the secondary effect of making testing easier: