我需要使用用户输入替换文件NOUN
中的占位符VERB
,ADJ
,ADV
和solution09.txt
。
Madlib solution09.txt:
有一天,我正在看着我的儿子[ADV]和他的[NOUN]一起玩。他假装[NOUN]是[ADJ]。几分钟后,他假装[VERB],因为其中一个[NOUN]开走了。当我向他询问这件事的时候,他[ADV]说,当[NOUN] [VERB]因为[NOUN]不能真的[VERB]时,这很有趣。
我想我已成功将文件放入字符串中,但我必须读取字符串,并用用户输入替换占位符。一旦我更换,我需要输出新的madlib。我将用户输入变为变量,但我不确定如何使用用户输入正确替换占位符。
当前代码:
file = File.open("solution09.txt", "r")
contents = file.read
puts "Enter a noun: "
noun = gets.chomp
puts "Enter a verb: "
verb = gets.chomp
puts "Enter an adjective: "
adj = gets.chomp
puts "Enter an adverb: "
adv = gets.chomp
if file.include?('NOUN')
file1= file.gsub("[NOUN]", noun, "[VERB]", verb, "ADJ", adj, "ADV", adv)
end
答案 0 :(得分:1)
您还可以构建替换哈希:
filename = "solution09.txt"
contents = File.read(filename)
replacements = {}
puts "Enter a noun: "
replacements['[NOUN]'] = gets.chomp
puts "Enter a verb: "
replacements['[VERB]'] = gets.chomp
puts "Enter an adjective: "
replacements['[ADJ]'] = gets.chomp
puts "Enter an adverb: "
replacements['[ADV]'] = gets.chomp
并将其传递给gsub
:
contents.gsub(Regexp.union(replacements.keys), replacements)
Regexp.union
创建一个匹配任何给定键的模式。
答案 1 :(得分:0)
您的代码应该是
filename = "solution09.txt"
contents=File.read(filename)
puts "Enter a noun: "
noun=gets.chomp
puts "Enter a verb: "
verb=gets.chomp
puts "Enter an adjective: "
adj=gets.chomp
puts "Enter an adverb: "
adv=gets.chomp
if contents.include?('NOUN')
{ "\[NOUN\]" => noun,
"\[VERB\]" => verb,
"\[ADJ\]" => adj,
"\[ADV\]" => adv
}.each do |key, value|
contents.gsub!(key, value)
end
File.open(filename, "w") { |f| f << contents }
end
您需要单独的读写操作。还有其他方法可以做到这一点
您可以看到如何处理单个文件指针https://stackoverflow.com/a/10173112/1380263
你也可以使用与shell交互的ruby方法并使用sed命令(system,backticks,peopen)
真的取决于最适合你的情况
答案 2 :(得分:0)
file = File.read("solution09.txt")
.gsub(/\[(NOUN|VERB|ADJ|ADV)\]/) do
part = case $1
when "NOUN" then "a noun"
when "VERB" then "a verb"
when "ADJ" then "an adjective"
when "ADV" then "an adverb"
end
puts "Enter #{part}: "
gets.chomp
end