使用模块(命名空间)完成教程。 我收到以下错误:
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,并且没有显示&lt;&lt;的方法。所以我希望实例变量@comment是一个对象列表,但它是一个单个对象。我是否正确地说,在实例化博客帖子对象时,我应该使用包含内容的列表初始化评论?单击博客评论?
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
答案 0 :(得分:2)
基于您的module.rb,在初始化Post对象时,您将Post.comments指定为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 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 :(得分:1)
当你处理数组时,但是期望单个值可能作为输入出现,你可能想要使用ruby magick:
value = *[arg]
无论arg是否为数组,都将保存一个数组:
arg = [1,2,3]
value = *[arg]
# => [
# [0] [
# [0] 1,
# [1] 2,
# [2] 3
# ]
# ]
arg = 1
value = *[arg]
# => [
# [0] [
# [0] 1
# ]
# ]
因此,在您的情况下,您可能希望使用单个注释或数组初始化对象:
@comments = [*options[:comments]]
会做的伎俩。问题是你在调用Comment
(第四个参数)时传递了单个Blog::Post.new
对象。
UPD:感谢@PatriceGahide,错误地处理了nil
。