2016-02-28 48 views
0

我初始化一個新對象的對象並設置屬性後設置屬性的方法(因爲有此特定對象沒有屬性):呈現形式,像這樣之前創建初始化

def new 
    Book.new title: nil, author: nil, genre: nil, language: nil, ect... 
end 

這對我來說看起來像是一種代碼味道。

我試圖在模型中的方法中設置屬性,所以我可以通過使用:Book.new.set_attributes來提高可讀性。所以我在書模型set_attributes方法看起來像:

def set_attributes 
    {posted: nil, company: nil, poster: nil, city: nil, state: nil, title: nil, body: nil, keywords: nil} 
end 

然而,這並不正常工作(帶或不帶{}括號內)。使用.new後可以調用方法嗎?

+0

你有沒有到這個好地方? – jvillian

回答

2

Ruby的構造方法是initialize,而不是new。您不應該嘗試定義一種名爲new的方法。做類似:

class Book 
    attr_accessor :title, :author 
    def initialize(title = nil, author = nil) 
    @title = title 
    @author = author 
    end 
end 
0

你不需要初始化nil值。當調用Book.new時,任何未在散列中提供的值(例如Book.new(標題:'Bozo',作者:'Clown'))將自動爲零。

相關問題