2015-08-23 55 views
0

Ruby中是否可以使用類方法實例化另一個類的另一個對象?從單獨的類對象中創建新類對象的實例

我花了很多時間來研究Google,Ruby文檔和Stack Overflow,以便回答我的查詢,因此我將這個問題作爲最後的手段發佈。

兩個等級,用戶博客。在用戶下面我試圖創建一個對象的新實例博客,並帶有一些屬性。

在類用戶有2種方法;

class User 
    attr_accessor :blogs, :username 

    def initialize(username) 
    self.username = username 
    self.blogs = [] 
    end 

    def add_blog(date, text) 
    self.blogs << [Date.parse(date),text] 
    new_blog = [Date.parse(date),text] 
    Blog.new(@username,date,text) 
    end 
end 

使用上述add_blog我想初始化&發送一個新的對象到博客類。

class Blog 
    attr_accessor :text, :date, :user 
    def initialize(user,date,text) 
    user = user 
    date = date 
    text = text 
    end 
end 
+0

什麼是錯誤的屬性做到這一點? –

+0

如果實例化一個用戶對象:哈里= User.new( 「harry1」) - 把harry.user結果: 未定義的方法'用戶」爲#<用戶:0x007fdc530c2f60>(NoMethodError) – Harry

+0

哈里已經是用戶,所以你需要調用'puts harry.username' – Meier

回答

1

是的,可以使用類方法實例化另一個類的另一個對象。我們ruby程序員一直在做這件事。

您是否希望用戶的blogs屬性擁有一組博客?因爲你的代碼只是把一個日期文本tupel放到數組中。

我覺得你想要做這樣的事情在你的用戶等級:

def add_blog(date, text) 
    parsed_date = Date.parse(date) 
    new_blog = Blog.new(@username, parsed_date, text) 
    self.blogs << new_blog 
    new_blog 
    end 

我已經表現出一步後一步,但你可以結合幾行。最後一行返回新博客,如果您只希望博客成爲博客數組的一部分,則可能不需要它。

+0

謝謝!這些都是非常有用的解決方案。但是當時我期待能夠將這個新對象稱爲Blog的一個實例,因爲它已經使用上面的Blog.new創建,這可能嗎? – Harry

+0

是的。它只取決於最後一行,它告訴ruby你在方法中返回的內容。在我的實現中,新的Blog對象被返回,您可以調用其他方法。 – Meier

+0

您也可以通過用戶訪問博客,如下所示:harry.blogs [0] .text – Meier

1

看起來你的代碼有一些缺陷。以下是已更正的代碼: 您並未使用@爲實例變量賦值,而是將日期設置爲@blogs而不是Blog對象。

如果你想的User例如從add_blog傳遞給Blog,您可以使用self代表User類的當前實例。如果你想攜帶只是一些屬性,那麼,你可以參考使用@attribute_nameself.attribute_name語法

require "date" 
class User 
    attr_accessor :blogs, :username 

    def initialize(username) 
    @username = username 
    @blogs = [] 
    end 

    def add_blog(date, text) 
    @blogs << Blog.new(@username, Date.parse(date),text) 
    self 
    end 

    def to_s 
    "#{@username} - #{@blogs.collect { |b| b.to_s }}" 
    end 
end 

class Blog 
    attr_accessor :text, :date, :user 

    def initialize(user,date,text) 
    @user = user 
    @date = date 
    @text = text 
    end 

    def to_s 
    "Blog of #{user}: #{@date} - #{@text}" 
    end 
end 

puts User.new("Wand Maker").add_blog("2015-08-15", "Hello") 
# => Wand Maker - ["Blog of Wand Maker: 2015-08-15 - Hello"]