How do I get rid of this RunTimeError when trying some code out of Chapter 12 of the Beginning Ruby book?

吃可爱长大的小学妹 提交于 2019-12-12 03:55:01

问题


Sorry if this is a total newbie question, but I am not sure how to solve this problem. I'm currently getting these errors when I try to run the code below:

bot.rb:58:in `rescue in initialize': Can't load bot data (RunTimeError)

bot.rb:55:in `initialize'

basic_client.rb:3:in `new'

basic_client.rb:3:in `<top (required)>'

Here is the source code for bot.rb, and the error appears to be at the "@data = YAML.load(File.open(options[:data_file]).read)" part.

# A basic implementation of a chatterbot
class Bot
  attr_reader :name

  # Initializes the bot object, loads in the external YAML data
  # file and sets the bot's name. Raises an exception if
  # the data loading process fails.
  def initialize(options)
    @name = options[:name] || "Unnamed Bot"
    begin
      @data = YAML.load(File.open(options[:data_file]).read)
    rescue
      raise "Can't load bot data"
    end
  end

This is the source code for basic_client.rb file:

require './bot'

bot = Bot.new(:name => ARGV[0], :data_file => ARGV[1])

puts bot.greeting

while input = $stdin.gets and input.chomp != 'end'
  puts '>> ' + bot.response_to(input)
end

puts bot.farewell

If anyone could help me that'd be great. Also if you need more information or clarification in regards to the problem, I can provide that too.

Thank you!


回答1:


Change the rescue so that you can see the full message:

 rescue => e
  raise "Can't load bot data because: #{e}"

Then I would say that getting an error there means that either your file is malformed (check its syntax with http://yamllint.com/) or the path is not correct. You need to make sure you are correctly passing the path of your yaml file to basic_client.rb as the second argument (ARGV[1]):

ruby basic_client.rb "C3PO" "bot.yml"

I'm not sure how "bot.yml" should look like, but it must be the data that you expect to be in your @data variable.



来源:https://stackoverflow.com/questions/19470239/how-do-i-get-rid-of-this-runtimeerror-when-trying-some-code-out-of-chapter-12-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!