Is there any special way to define a class in Ruby that will have just
one instance object? I do not need even a class name.
I mean something simple like that
obj = class { def foo; puts “Foo”; end }.new
obj.foo
Is there any special way to define a class in Ruby that will have just
one instance object? I do not need even a class name.
I mean something simple like that
obj = class { def foo; puts “Foo”; end }.new
obj.foo
You can use the singleton lib, look:
Your “new” method will become a private method and you`ll instantiate
your
object using “.instance”
I hope to be helpful.
Thank you Wender J. for your fast answer. I read the referenced
documentation but I do not think it is what I was looking for. In fact,
I am not trying to avoid multiple instances. I devise the use of an
object of a class as a mean to access users methods from within a class
I am writing. Something like that;
class Anyname
def something
end
def something_else
end
end # Anyname
obj = Anyname.new
another_obj = MyClass.new(obj)
another_obj.anything
another_obj.anything_else
class MyClass
def initialize(user_obj)
@user = user_obj
end
def anything
@user.something if @user.respond_to?(“something”)
end
def anything_else
@user.something_else if @user.respond_to?(“something_else”)
end
end # MyClass
In this case, it is pointless to create more than one object Anyname.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs