我對Ruby的理解是,'new'關鍵字總是和一個類名相結合以創建一個類的新實例。在下面的代碼中找到了https://gist.github.com/e9c0da1a6e92dd12cbc7,這是作爲Newbies大賽的Ruby編程挑戰解決方案提交的,作者使用「new」關鍵字三次而不實例化一個類。Ruby:沒有類的'new'
在一種情況下,new(0,0)被分配給常量CLOSED。在另一種情況下,new(open,close)是函數的返回值。爲什麼這樣做?使用這種方式時,「新」是什麼?它是什麼創造的?
class OpenHours
attr_reader :open, :close
def initialize(open, close)
@open, @close = open, close
end
def duration
@duration ||= @open < @close ? @close - @open : 0
end
CLOSED = new(0, 0) #first new
def self.parse(open, close)
open = Time.parse(open)
close = Time.parse(close)
open = TimeUtils::seconds_from_midnight(open)
close = TimeUtils::seconds_from_midnight(close)
new(open, close) #second new
end
def offset(seconds)
self.class.new([@open, seconds].max, @close) #third new
end
end
那麼self.parse方法返回OpenHours的新實例(打開,關閉)?它不應該分配給某些東西嗎? – BrainLikeADullPencil