Access variables in singleton?

S

Steve V

I created the following small singleton class, but it seems that my
variables are ignored.

require 'singleton'

class Context
include Singleton

@companyname = "acme"

def company()
return @companyname
end

def change(name)
@companyname = name
end

end

If I set the @companyname variable within the company function, and then
return it, the value is there. After that though, it seems that the variable
just disappears. What am I doing wrong?

Thanks,
Steve
 
B

Ben Giddings

I created the following small singleton class, but it seems that my
variables are ignored.

require 'singleton'

class Context
include Singleton

@companyname = "acme"

Wrong context, this is defined within the "Context" class definition, not
within the one object (instance of Context) that you create. What you
want is:

def initialize
@companyname = "acme"
end

Singleton will make "new" private, but you still want to use "initialize"
which will be called by "instance"

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,920
Members
47,464
Latest member
Bobbylenly

Latest Threads

Top