使用模塊(命名空間)瀏覽教程。 我收到以下錯誤: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
不錯,很優雅。如果發送空值,那麼數組仍然會被創建? – surfer190 2014-10-30 08:50:03
你可以自己試試:)它肯定會被創建,請注意'|| []'在'* [options [:comments] ||中[]]'。 – mudasobwa 2014-10-30 08:51:53
不,它不會按預期那樣做。你想'@comments = [*選項[:評論]]' – 2014-10-30 08:57:11