LoginSignup
1
0

More than 1 year has passed since last update.

【オブジェクト指向】コンストラクタ

Last updated at Posted at 2021-12-02

コンストラクタとは

Rubyのようなオブジェクト指向のプログラミング言語で使われる機能の1つで、オブジェクトを生成した際に1度だけ実行される機能を指す名称。
initialize という名前のメソッドは自動的に private に設定される。

initialize

  • 「new」メソッドが実行された際に自動的に呼び出される
class Sample
   def initialize
     p '初期化処理'
   end
end  

s = Sample.new
"初期化処理"
=> #<Sample:0x0000557ab2005168>
  • インスタンスを生成するnewメソッドで引数を指定することで、その値をインスタンス変数に設定することが可能
class Sample
  def initialize(name)
    @name = name  
  end

  def execute() 
    p @name + ' hello'
  end  
end

sample1 = Sample.new('kato') 
=> #<Sample:0x0000557ab2595ec0 @name="kato">
sample2 = Sample.new('takagi') 
=> #<Sample:0x0000557ab25bd740 @name="takagi">

sample1.execute 
=> "kato hello"
sample2.execute
=> "takagi hello"
  • initializeを実行しない場合はクラスをnewして、インスタンスメソッドへ引数を引き渡してという処理を、各処理毎に毎回設定しなければいけない。
class Sample
  def name=(name)
    @name = name
  end

  def hello
    p @name + ' hello'
  end
end

s = Sample.new
s.name = 'kato'
p s.execute
=> "kato hello"

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0