看板 Ruby 關於我們 聯絡資訊
------------------------------- test.rb ------------------------------- class S puts 'Just started class S' puts self module M puts 'Nested module S::M' puts self end puts 'Back in the outer level of S' puts self def test puts "test" end end ss = S.new ss.test -------------------------------- -------------------------------- output: -------------------------------- Just started class S S Nested module S::M S::M Back in the outer level of S S test -------------------------------- 今天發現就算沒有instance S這個class 他的內容還是會先跑過一遍 但之後要讓它再跑一次好像就沒辦法了 請問這樣的寫法會有什麼用途嗎? 還是說應該要避免這樣的寫法呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 163.32.125.195 ※ 文章網址: https://www.ptt.cc/bbs/Ruby/M.1437884529.A.C50.html
uranusjr: 沒什麼好避免的, 本來就是這樣, 可用可不用 07/26 12:55
uranusjr: 要說用途的話可以用來模仿例如 C 的 #ifdef 條件編譯 07/26 12:56
showken: 謝謝~了解了 07/26 21:22
ihower: 拿來做metaprogramming啊, Rails 超愛這招 07/26 23:10
showken: metaprograming好酷,剛剛還找到這個 07/27 13:47
showken: https://goo.gl/9jEq63 給有需要的人看看 07/27 13:48
showken: 目前還看不懂,不過感覺很厲害 07/27 13:49