0

对于如何将方法文本保存到 txt 文件中,我得到了你们很好的回应,但我现在遇到了不同的问题。问题是程序生成一个随机标题并在命令提示符下打印它,但它在文件中保存了一个完全随机的标题。例如,如果我运行程序,它会生成一个标题“Big Thing”,但在 txt 文件中它会保存“Small Game”。有没有办法让程序保存与在 CP 中打印的相同标题?代码看起来像这样:

class Generator
  def title_adj
    title_adj = [
       "Big",
       "Small"]
    item_title_adj = title_adj[rand(title_adj.length)]
  end
  def title_noun
    title_noun = [
       "Thing",
       "Game"]  
    item_title_noun = title_noun[rand(title_noun.length)]
  end
  def title
    title_adj + title_noun
  end
  def initialize(io)
    @io = io
  end
  def all
    @io.puts "Your story is called: " + title
  end
end

fict_gen = Fiction_Generator.new(STDOUT)
def prompt
  print "> "
end
puts "Do you want to generate a new title or read the existing one?"
puts "1 = Generate, 2 = Read existing"

prompt; r = gets.chomp
if r == "1"
  fict_gen.all

  File.open("Story.txt", "a+") do |file|
    fict_gen = Fiction_Generator.new(file)
    fict_gen.all
  end

elsif r == "2"
  File.open("Story.txt").each_line{ |s|
  puts s
  }
end
4

1 回答 1

0

问题是您每次调用该方法时都会随机生成标题。自己证明这一点:

a = Generator.new(STDOUT)
a.title #=> "BigThing"
a.title #=> "SmallThing"
a.title #=> "BigThing"

解决方案,将标题存储在实例变量中:

def title
  @title ||= %w|Big Small|.sample + %w|Thing Game|.sample
end

运算符仅在接收者是或||=时才执行赋值。nilfalse

于 2013-03-22T18:15:50.910 回答