2014-02-10 24 views
0

什麼將:: Schedule.new在下面的代碼中做什麼?是不是缺少::前面的東西?模塊中的雙冒號,調用類構造函數?

module Schedulable 
     attr_writer :schedule 

     def schedule 
     @schedule ||= ::Schedule.new 
     end 

     def schedulable?(start_date, end_date) 
     !scheduled?(start_date - lead_days, end_date) 
     end 

    .. 

    end 
+0

嗨,這個職位應該回答你的問題:http://stackoverflow.com/questions/3009477/what-is-rubys-double-colon-all-關於 –

+0

我已經閱讀過這篇文章,但是我沒有看到它在這裏如何回答我的具體問題......謝謝 –

+0

調用你的def schedule會創建一個Schedule類的新實例,但前提是它已被定義(當然) (@)schedule:irb(main):013:0> schedule =># irb(main):014:0> @schedule =>#

回答

1

如果你把什麼在::面前 - 它只是說在解釋使用全球範圍內。

即查看對象層次結構的頂層,並在那裏尋找Schedule類。

0

它創建一個Schedule類的新實例(需要定義),但只有在@schedule尚未定義的情況下。所以在它前面的「或者等於」。

這裏它的一個簡單的測試:

irb(main):013:0> schedule 
    => #<Schedule:0x3b9ccf62> // new Schedule instance 
    irb(main):014:0> @schedule 
    => #<Schedule:0x3b9ccf62> // same Schedule instance 
    irb(main):015:0> @schedule = "foooo" // new value for @schedule 
    => "foooo" 
    irb(main):016:0> schedule // now method returns new value and no new instance of Schedule 
    => "foooo" 
相關問題