LoginSignup
5
3

More than 5 years have passed since last update.

メタプログラミングRubyメモ

Last updated at Posted at 2016-08-08

5章 クラス定義

クラスはすぐに実行される

  • rubyは定義文と実行文という定義が無い
class Hoge
  puts 'hoge'
end
  • クラスを定義したと同時に中身が実行される
  • 既に定義しているクラスの場合はそのクラスをオープンにし使うことが出来る
  • defの中は定義時点では実行されない
  • すぐに実行されるので、rubyではコンストラクタは不要

既存のクラスを拡張

  • 既存のクラスもオープンにして拡張できる
class String
  def test
    puts 'test'
  end
end

'ruby'.test

test

=> nil
pluralizeはオープンクラスの機能を使って、railsがStringクラスを拡張して定義しているメソッド
  • class_evalを使うとクラスの参照を受け取ると、動的にクラスをオープンにして拡張することも出来る
5
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
5
3