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 特異メソッド・特異クラス わかりやすく解説!

Last updated at Posted at 2025-03-02

はじめに

Rubyの独自機能 特異メソッド・特異クラスについてわかりやすく解説します❗️

目次

  1. 特異メソッドとは?
  2. 特異クラスとは?
  3. まとめ

特異メソッドとは?

「ある特定のオブジェクトだけが使える特別なメソッド」

普通のインスタンスメソッドは、クラス全体に適用される。
一方、特異メソッドは「そのオブジェクトだけ」に追加される!

class Cat
  def speak
    "にゃー"
  end
end

tama = Cat.new
shiro = Cat.new

# tama だけに特異メソッドを定義!
def tama.speak
  "ゴロゴロ…"  # tama だけ特別な喋り方をする
end

puts tama.speak  # => "ゴロゴロ…"
puts shiro.speak # => "にゃー"(元のクラスのメソッドが適用)

👉 tama だけが特別な speak メソッドを持っている!
👉 shiro には影響なし!

特異クラスとは?

「特異メソッドを格納するための隠れクラス」

実は、Ruby ではオブジェクトごとに専用のクラス(特異クラス)が作られる!
これが特異メソッドの正体。

特異クラスへのメソッド追加

tama = "猫"

class << tama
  def speak
    "ゴロゴロ…"
  end
end

puts tama.speak  # => "ゴロゴロ…"

👉 class << tama の中で定義すると、そのオブジェクトの特異クラスにメソッドが追加される!

特異クラスの階層を確認

tama = "猫"
def tama.speak
  "ゴロゴロ…"
end

puts tama.singleton_class  # => #<Class:#<String:0x0000...>>
puts tama.singleton_class.superclass  # => String

👉 singleton_class で特異クラスを取得できる
👉 特異クラスは元のクラス(String)を継承している

まとめ

  • 特異メソッド = 特定のオブジェクトだけが持つメソッド
  • 特異クラス = 特異メソッドを格納するための隠れクラス
  • 特異クラスにメソッド追加:def {オブジェクト名}.{メソッド名} で定義
  • 特異クラスを直接操作:class << {オブジェクト名} で定義

Ruby のクラス構造が柔軟なのは、この特異クラスのおかげ!ふむふむ..
これで、オブジェクトごとにカスタマイズできるんだな! 😆✨

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?