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?

···

--
Posted via http://www.ruby-forum.com/.

Yes:

lambda {
  x = 0

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

}.call

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 method `x' for
main:Object (NameError)

···

--
Posted via http://www.ruby-forum.com/.

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.

···

--
Posted via http://www.ruby-forum.com/.