如何让ruby将相同的随机生成的标题保存到txt中?

时间:2013-03-22 18:00:16

标签: ruby

我得到了很好的回复,我们如何将方法文本保存到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

1 个答案:

答案 0 :(得分: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

如果接收方为||=nil,则false运算符仅执行分配。