Ruby Goldへの道 day15
以下のサイトでruby gold取得に向けて毎日一回Goldチャレンジを行い間違えた問題を簡単にまとめる。 rex.libertyfish.co.jp
15日目 得点 86点/100点中
- prepend
- メソッド探索はselfの後に追加される
- include
- メソッド探索はselfの前?
module M def foo super puts "M#foo" end end class C2 def foo puts "C2#foo" end end class C < C2 def foo super puts "C#foo" end prepend M # include M end C.new.foo # C2#foo # C#foo # M#foo # prependをinludeに変更した場合 # C2#foo # M#foo # C#foo
- Refeinment
- クラスメソッドを再定義するにはsingleton_classを使用する
self.メソッド
として定義しない
- クラスメソッドを再定義するにはsingleton_classを使用する
class C def self.m1 200 end end module R refine C do def self.m1 100 end end # refine C.singleton_class do # def m1 # 100 # end # end end using R puts C.m1 #=> 200
- printは改行しない
begin print "liberty" + :fish.to_s rescue TypeError print "TypeError." rescue print "Error." else print "Else." ensure print "Ensure." end #=> libertyfishElse.Ensure.
module_eval
をブロックで定義した定数はモジュール内で定義したことになる
mod = Module.new mod.module_eval do EVAL_CONST = 100 end puts "EVAL_CONST is defined? #{mod.const_defined?(:EVAL_CONST)}" #=> EVAL_CONST is defined? true puts "EVAL_CONST is defined? #{Object.const_defined?(:EVAL_CONST)}" #=> EVAL_CONST is defined? true