2014-10-30 150 views
0

使用模塊(命名空間)瀏覽教程。 我收到以下錯誤:Ruby未定義方法'<<'for class?

blog.rb:25:in `insert_random_comment': undefined method `<<' for 
    #<Blog::Comment:0x007f1370368be0> (NoMethodError) 
    from modules.rb:13:in `<main>' 

在insert_random_comment我把這個類和方法。班級是Blog :: Comment,並且沒有顯示< <的方法。所以看來我期待實例變量@comment是一個對象列表,但它是一個單一的對象。我是否正確地說,在實例化Blog博客文章對象時,我應該用帶有單個博客評論內容的列表初始化評論?

module.rb

post = Blog::Post.new author: "Stevie G", 
         title: "A title", 
         body: "A body", 
         comments: Blog::Comment.new( user: "Jeffrey Way", 
                 body: "A Comment") 

post.insert_random_comment 

blog.rb

module Blog 

    class Post 
     attr_reader :author, :title, :body, :comments 

     def initialize options 
       @author = options[:author] 
       @title = options[:title] 
       @body = options[:body] 
       @comments = options[:comments] || [] 
     end 

     #*splat (only 1 splat in method signature) 
     #first param, *comments 
     # insert_comments first, second, *thirds, options, &block 
     def insert_comment first, second, *thirds, options, &block 
       comments.each { |c| @comments << c } 
     end 

     def insert_random_comment 
       p @comments.class 
       p @comments.methods 
       @comments << Comment.new(user: "jose Mota", body: "A body") 
     end 
    end 

    class Comment 
     attr_reader :user, :body 

     def initialize options 
       @user = options[:user] 
       @body = options[:body] 
     end 
    end 
end 

回答

2

此基礎上你module.rb,你會當你初始化一個帖子對象分配Post.comments作爲評價對象。

post = Blog::Post.new author: "Stevie G", 
         title: "A title", 
         body: "A body", 
         comments: Blog::Comment.new( user: "Jeffrey Way", 
                 body: "A Comment") #This is an object of Comment 

所以,你可以:

post = Blog::Post.new author: "Stevie G", 
         title: "A title", 
         body: "A body", 
         comments: [Blog::Comment.new( user: "Jeffrey Way", 
                 body: "A Comment")] #This is an Array of Comments 
1

當你正在處理數組,但希望爲輸入可能會出現單個值,你可能需要使用紅寶石magick:

value = *[arg] 

將持有陣列,儘管參數是否是數組:

arg = [1,2,3] 
value = *[arg] 
# => [ 
# [0] [ 
#  [0] 1, 
#  [1] 2, 
#  [2] 3 
# ] 
# ] 

arg = 1 
value = *[arg] 
# => [ 
# [0] [ 
#  [0] 1 
# ] 
# ] 

所以,你的情況你可能想用單留言或數組初始化對象:

@comments = [*options[:comments]] 

會做的伎倆。問題是actially您在調用中傳遞的單Comment對象Blog::Post.new

UPD(第四個參數):由於@PatriceGahide,處理的nil被錯誤地進行。

+0

不錯,很優雅。如果發送空值,那麼數組仍然會被創建? – surfer190 2014-10-30 08:50:03

+0

你可以自己試試:)它肯定會被創建,請注意'|| []'在'* [options [:comments] ||中[]]'。 – mudasobwa 2014-10-30 08:51:53

+0

不,它不會按預期那樣做。你想'@comments = [*選項[:評論]]' – 2014-10-30 08:57:11

相關問題