Static local variables for methods?

I have this:

def valid_attributes
{ :email => “some_#{rand(9999)}@thing.com” }
end

For Rspec testing right? But I would like to do something like this:

def valid_attributes
static user_id = 0
user_id += 1
{ :email => “some_#{user_id}@thing.com” }
end

I don’t want user_id to be accessible from anywhere but that method,
is this possible with Ruby?

Yes:

lambda {
x = 0

Kernel.send(:define_method, :meth_name) {
x += 1
puts x
}

}.call

meth_name()
meth_name()
meth_name()

puts x

–output:–
1
2
3
ruby.rb:16:in <main>': undefined local variable or methodx’ for
main:Object (NameError)

You might want to change Kernel to whatever class your def is in to
limit the scope of the def, like this:

class Dog
end

lambda {
x = 0

Dog.send(:define_method, :meth_name) {
x += 1
puts x
}

}.call

d = Dog.new
d.meth_name()
d.meth_name()
d.meth_name()

meth_name()

–output:–
1
2
3
ruby.rb:20:in <main>': undefined methodmeth_name’ for main:Object
(NoMethodError)

But maybe you just want:

def valid_attributes
@__user_id ||= 0
@_user_id += 1
{ :email => "some
#{@__user_id}@thing.com" }
end

This is simpler; just choose an instance variable name which is highly
unlikely to clash with anything else.

Of course, each instance of this object will have its own counter then.
If that’s not what you want, I’d use an instance variable within the
class itself.