0

我正在尝试运行这样的代码:

class Run_Fiction_Generator < Fiction_Generator
  def generate_story
    puts "Title: \"#{generator.title} #{generator.random_date}\""
    puts "---------"
    puts generator.story
  end
end

prompt = '>'

puts "Hello Welcome to Fiction Generator"
puts "First a little about me: "
puts ""

generator = Run_Fiction_Generator.new

puts "This amazing Fiction Generator was created by: #{generator.created_by}"
puts "He's a student with ID number: #{generator.student_id} "
puts ""
puts "Okay now your story! Enter '1' if you want to generate a story now, or '2' if you don't want to"
print prompt
answer = gets.chomp

if answer == "1"
  generate_story
else
  puts "It was nice meeting you, catch ya later!"
end

但是语句generator_story中的方法不断抛出这个错误:if

main:Object (NameError) 的未定义局部变量或方法“generate_story”

我的印象是我已经在我的代码中定义了该方法。谁能告诉我哪里出错了?

4

3 回答 3

6

generate_story是一种方法,Run_Fiction_Generator它应该像这样调用:

generator.generate_story
于 2012-11-01T23:19:40.113 回答
1

您的另一个问题是您如何访问生成故事方法中的变量和方法。尝试这个:

class Run_Fiction_Generator < Fiction_Generator
  def random_date
    "10/20/2012"
  end

  def title
   "Spooky, Late Halloween Story"
  end

  def generate_story
    puts "Title: \"#{title} #{random_date}\""
    puts "---------"
    puts @story
  end
end
于 2012-11-01T23:38:04.047 回答
0

顺便说一句:类名是“错误的”

使用 CamelCase 作为类名,而不是 '_ 来分隔。

于 2013-11-06T19:19:14.587 回答