如何让ruby将相同的随机生成的标题保存到txt中?
我从你们那里得到了一个很好的回复,关于如何将方法文本保存到txt文件中,但我现在遇到了一个不同的问题。问题是程序生成一个随机标题并在命令提示符下打印,但它在文件中保存了一个完全随机的标题。例如,如果我运行该程序,它将生成一个标题“Big Thing”,但在txt文件中它将保存“Small Game”。有没有办法让程序保存与在CP中打印的标题相同的标题?代码如下所示:如何让ruby将相同的随机生成的标题保存到txt中?,ruby,Ruby,我从你们那里得到了一个很好的回复,关于如何将方法文本保存到txt文件中,但我现在遇到了一个不同的问题。问题是程序生成一个随机标题并在命令提示符下打印,但它在文件中保存了一个完全随机的标题。例如,如果我运行该程序,它将生成一个标题“Big Thing”,但在txt文件中它将保存“Small Game”。有没有办法让程序保存与在CP中打印的标题相同的标题?代码如下所示: class Generator def title_adj title_adj = [ "Big",
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
问题是,每次调用该方法时,都会随机生成标题。你自己证明这一点:
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
时执行赋值。哇,第六通道需要重构帮助!斯达!