0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

クラスメソッド

Last updated at Posted at 2020-07-15
1 / 2

##クラスメソッドとは
クラスに関連が深いものの、一つ一つのインスタンスに含まれるデータを使わないメソッド

#####クラスメソッドを定義する方法1

class クラス名
  def self.クラスメソッド
  #クラスメソッドの処理
 end
end

#####クラスメソッドを定義する方法2


class クラス名
  class << self
    def クラスメソッド
      #クラスメソッドの処理
    end
  end
end

クラスメソッドを呼び出す場合は以下のようにする

クラス名.メソッド名
class Food
  def initialize(name)
    @name = name
  end

  #self.をつけるとクラスメソッドになる
  def self.create_foods(names)
    names.map do |name|
      Food.new(name)
    end
  end

  #インスタンスメソッド
 def eat
    "I will eat an #{@name}."
  end
end

names = ['apple', 'octopus']
#クラスメソッドの呼び出し
foods = Food.create_foods(names)
foods.each do |food|
  puts food.eat
end

#=> I will eat an apple.
#   I will eat an octopus.

#参照
プロを目指すためのRuby入門

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?