0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Ruby】特異メソッドはあるオブジェクトだけが持つメソッドである

Posted at

特異メソッドとは特定のオブジェクト一つだけが持つメソッドのこと。

class Dog
  def bark
    "Woof!"
  end
end

# 2つのインスタンスを作成
dog1 = Dog.new
dog2 = Dog.new

# dog1にだけ特異メソッドを定義
def dog1.jump
  "Jump high!"
end

# 実行結果
dog1.bark  # => "Woof!"
dog2.bark  # => "Woof!"
dog1.jump  # => "Jump high!"
dog2.jump  # => NoMethodError (未定義のメソッド)

以下のような実装も特異メソッド。

class Dog
  def self.species
    "Canine"
  end
end

# 実行してみると
Dog.species        # => "Canine" (クラスメソッドとして実行可能)
dog = Dog.new
dog.species        # => NoMethodError (インスタンスからは実行できない)

この実装では、Dogのインスタンスがすべてspeciesを実行できるため、特異メソッドではないように見えるが、クラスメソッドはクラスオブジェクトの特異メソッドとして定義されるからこれらも特異メソッドと捉えることができる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?