LoginSignup
4
3

More than 1 year has passed since last update.

Ruby のオープンクラスとは (メタプログラミングRuby)

Last updated at Posted at 2018-06-02

Rubyでは定義済みのクラスでも、何度でも開いて、中身をいじることが出来る。
これをオープンクラスという。

クラスを定義

クラスメソッドを1個作る。

class A
  def some_method
    p :some_method
  end
end

また定義

メソッドをもう1個作る。

class A
  def new_method
    p :new_method
  end
end

すると‥

どちらのメソッドも呼べるようになる

A.new.some_method # :some_method
A.new.new_method # :new_method

なんでもアリ

Integer クラスなど、元から存在するクラスでもオープンして書き換えられる。

class Integer
  def some_method
    p :some_method
  end
end

1.some_method # :some_method
2.some_method # :some_method

参考

  • メタプログラミングRuby

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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