オブジェクトに特異メソッドをくっつけるいくつかの方法
その1
もっとも一般的なやり方。
str="Hello World" def str.say puts self end str.say
その2
特異クラスを定義して、その中でメソッド定義する
str="Hello World" class << str def say puts self end end str.say
その3
moduleを定義して、extendする
str=String.new("Hello World") module Say def say puts self end end str.extend Say str.say
これはRailsでありがちな方法ですね。
まとめるのに便利かもしれません。
その4
特異クラスを定義して、class_evalしてしまう
str="Hello World" class << str self end.class_eval do define_method(:say){puts "hello"} end str.say
この方法、意外といいかも。
evalなんで、いろいろ使える上に、1.9だとスピードも速い。
ちょっと自分の中で整理したくて書いてみただけです。
あんまり役に立つ情報じゃないかもね。