我正在通过JoséMota的The Fundamentals of Ruby课程学习Ruby,在课程结束后我遇到了这些错误,我不确定发生了什么。代码与Ruby版本为1.9.3的课程中的视频完全相同,但我有Ruby 2.0。
以下是代码:
blog.rb
:
# encoding: utf-8
require_relative "Tweetable"
module Blog
class Post
include Tweetable
attr_reader :author, :title, :body, :comments
def initialize options
@author = options[:author]
@title = options[:title]
@body = options[:body]
@comments = options[:comments] || []
end
def insert_comment *comments
comments.each { |c| @comments << c }
end
def insert_random_comment
@comments << Comment.new(user:"Kshitiz Rimal", body:"Thik chha keta")
end
end
class Comment
include Tweetable
attr_reader :user, :body
def initialize options
@user = options[:user]
@body = options[:body]
end
end
end
当我尝试从另一个文件加载模块时,代码为:
module.rb
:
require_relative "blog"
post = Blog::Post.new author: "Kshitiz Rimal",
title: "Hello new Post",
body: "This is a new body",
comments: Blog::Comment.new(user: "Random Name", body: "Good one")
post.insert_random_comment
我正在尝试在帖子中插入随机评论。我收到了以下错误:
Users/kshitizrimal/blog.rb:23:in `insert_random_comment': undefined method `<<' for #<Blog::Comment:0x007fd9b995ee40> (NoMethodError)
from modules.rb:8:in `<main>'
答案 0 :(得分:4)
@comments = options[:comments] || []
已分配给@comments
个Blog::Comment
个对象。但是类Blog::Comment
中没有定义实例方法#<<
。
现在,在行下面的方法insert_random_comment
会导致错误 -
@comments << Comment.new(user:"Kshitiz Rimal", body:"Thik chha keta")
上述石灰意味着
@comments.<<(Comment.new(user:"Kshitiz Rimal", body:"Thik chha keta"))
当您对课程Blog::Post
课程进行了大肆宣传时,您通过了以下内容: -
comments: Blog::Comment.new(user: "Random Name", ...
那是
的原因 @comments = options[:comments] || []
实际分配给Blog::Comment
的对象,而不是Array
。存在Array#<<
方法,但在您的情况下,#<<
实例上未调用Array
。
您包含Tweetable
,但该错误还确认该模块未向您的班级#<<
添加任何方法Blog::Comment
,因为该模块本身也没有“{1}}。 t定义了#<<
方法。
答案 1 :(得分:2)
我相信你module.rb
应该是:
require_relative "blog"
post = Blog::Post.new author: "Kshitiz Rimal",
title: "Hello new Post",
body: "This is a new body",
comments: [Blog::Comment.new(user: "Random Name", body: "Good one")]
post.insert_random_comment
这会将@comments
设置为列表,该列表支持<<
运算符...