How do I use a common object in ruby's class?
I would like to define it in the class method, so please tell me how to avoid initialize.
The image looks like this:
class Hoge
@obj=Fuga.new
def self.test
@obj.abcd
end
def self.test2
@obj.efg
end
end
The code written in the question would be fine, but if you define a class method for retrieving objects and use the delay initialization idiom, you will somehow behave well.
class Bar
def initialize
puts 'Initialized.'
end
def hello
puts 'Hello'
end
def bye
puts 'Bye'
end
end
class Foo
def self. hello
bar.hello
end
def self.bye
bar.bye
end
def self.bar
@bar||=Bar.new
end
end
# Calling Class Methods
Foo. hello
# =>Initialized.
# = > Hello
Foo.bye
# =>Bye
© 2024 OneMinuteCode. All rights reserved.