2012-10-30 43 views
0

虛擬屬性我有以下功能工作得很好有多個參數

def holiday_hours_for(holiday) 
    hours["holiday_hours"][holiday.to_s] if hours["holiday_hours"][holiday.to_s] 
end 

我只是瞭解虛擬屬性,和時遇到一些麻煩搞清楚這個功能的二傳手版本。如何實現此功能...

def holiday_hours_for(holiday)=(hours) 
    self.hours["holiday_hours"][holiday.to_s] = hours if hours["holiday_hours"][holiday.to_s] 
end 

謝謝!

更新:我想出了以下內容,這是最好的方式嗎?

def update_holiday_hours_for(holiday, hours_text) 
    self.hours = Hash.new unless hours 
    self.hours["holiday_hours"] = Hash.new unless hours["holiday_hours"] 
    self.hours["holiday_hours"][holiday.to_s] = hours_text.to_s 
    end 

回答

0

要理解的重要一點是setter方法在最後用「=」符號定義。像這樣:

def holiday_hours=(some_parameters) 
    # some code 
end 

這就像實例變量@holiday_hours的setter方法一樣。方法名稱是「holiday_hours =」,它需要一個或多個參數,根據您的應用程序的要求來派生屬性@holiday_hours的值。當Ruby看到一些代碼如

holiday.holiday_hours = some_value 

它調用你定義的setter方法。儘管此賦值中有一些空格不在setter方法中。紅寶石解釋這項任務作爲

holiday.holiday_hours=(some_value) 

調用holiday_hours假期對象=方法,用參數SOME_VALUE

這不是從您的文章中類是什麼在你的實例方法糾纏清楚,我能猜出變量hours_text是,但什麼是參數假期?

+0

假期將是一個指定哪個假期的參數。聖誕節,新年等 – Brandon

+0

我不認爲你正在使用虛擬屬性。你只是設置一個散列值。虛擬屬性是指爲一個對象調用一個setter方法,但實際上它沒有由setter命名的屬性。當該方法被調用時,它設置一個實際屬性。 –

+0

我明白了......謝謝! – Brandon