I want to use a common object in ruby's class.

Asked 2 years ago, Updated 2 years ago, 34 views

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

ruby

2022-09-30 16:58

1 Answers

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


2022-09-30 16:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.