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.
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
@@hashinto a class method. This has the secondary effect of making testing easier: