LoginSignup
0
0

More than 1 year has passed since last update.

クラスメソッドとインスタンスメソッドとinitializeメソッドの備忘録

Last updated at Posted at 2022-09-17

どれがクラスメソッド、インスタンスメソッド、initializeメソッドか思い出す為に簡単にですがメモします。

先に記述内容

class Vegetable

  def self.fresh
    puts "新鮮な野菜はいかがですか?"
  end
 
  def initialize(name, price)
    @name = name
    @price = price
  end
 
  def introduce
    puts "#{@name}は#{@price}円です"
  end
 end
 
 carrot = Vegetable.new("にんじん", 120)
 lettuce = Vegetable.new("レタス", 200)
 tomato = Vegetable.new("イチゴ", 160)
 
 Vegetable.fresh
 carrot.introduce
 lettuce.introduce
 tomato.introduce
結果
新鮮な野菜はいかがですか?
にんじんは120円です
レタスは200円です
イチゴは160円です

クラスメソッド

クラスオブジェクトから呼び出すためのメソッド
個別の情報によらず、共通の結果を返す動作を定義する
メソッド名の前にselfを.(ドット)で繋いで定義する。

class Vegetable
  def self.fresh
    puts "新鮮な野菜はいかがですか?"
  end
end
 
Vegetable.fresh

initializeメソッド

インスタンスが生成された瞬間に、生成されたそのインスタンスが実行する処理を定義するインスタンスメソッド。
クラス名.newに対して引数を渡すことでinitializeメソッドに値を渡すことができる。

class Vegetable
  def initialize(name, price)
    @name = name
    @price = price
  end
end
 
 carrot = Vegetable.new("にんじん", 120)
 lettuce = Vegetable.new("レタス", 200)
 tomato = Vegetable.new("イチゴ", 160)
 # インスタンス = クラス名.new

インスタンスメソッド

インスタンスが使用できるメソッド。
インスタンスごとの個別の情報(属性値)を使った処理に使用する。
インスタンス名.メソッド名で呼び出す。

class Vegetable

  def initialize(name, price)
    @name = name
    @price = price
  end
 
  def introduce
    puts "#{@name}は#{@price}円です"
  end
  
end
 
 carrot = Vegetable.new("にんじん", 120)
 lettuce = Vegetable.new("レタス", 200)
 tomato = Vegetable.new("イチゴ", 160)
 
 carrot.introduce
 lettuce.introduce
 tomato.introduce

以上になります。

0
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
0
0