実行時に継承するクラスを決める
はじめてのRubyの動的性に書かれていたプログラムを変えて試してみる
とりあえずMyclassの定義の前のnの値を変えれば継承するクラスが変わりました。
でもコメントアウトした部分のようにnの値を変えてみても継承されるクラスは同じでした。ということはRubyがクラスの定義を解釈する時のnの値でMyclassが何から継承されるか固定されてしまうということで良いのかな?
class Foo def print puts "I am Foo" end end class Bar def print puts "I am Bar" end end class Baz def print puts "I am Baz" end end names = [Foo,Bar,Baz] n = 0 # この値を変えれば結果も変わる class Myclass < names[n] end Myclass.new.print #=> I am Foo #n = 1 #Myclass.new.print #=> I am Foo #n = 2 #Myclass.new.print #=> I am Foo