infoMore than 5 years have passed since last update.
メタプログラミングRubyメモ
Last updated at Posted at 2016-08-08
5章 クラス定義
クラスはすぐに実行される
class Hoge
puts 'hoge'
end
- クラスを定義したと同時に中身が実行される
- 既に定義しているクラスの場合はそのクラスをオープンにし使うことが出来る
- defの中は定義時点では実行されない
- すぐに実行されるので、rubyではコンストラクタは不要
既存のクラスを拡張
class String
def test
puts 'test'
end
end
'ruby'.test
test
=> nil
pluralizeはオープンクラスの機能を使って、railsがStringクラスを拡張して定義しているメソッド
- class_evalを使うとクラスの参照を受け取ると、動的にクラスをオープンにして拡張することも出来る
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
What you can do with signing up