Natela Natela - 2 years ago 64
Ruby Question

Converting file to string and replacing string text with user input

I need to replace placeholders

NOUN
,
VERB
,
ADJ
, and
ADV
in a file
solution09.txt
with user input.

Madlib solution09.txt:


One day I was watching my son [ADV] play with his [NOUN]. He was pretending the [NOUN] were [ADJ]. After a few minutes he was pretending to [VERB], because one of the [NOUN] drove away. When i asked him about it he [ADV] said, umm it's funny when [NOUN] [VERB] because [NOUN] can't really [VERB].


I think I successfully put the file into a string, but I have to read the string, and replace the placeholders with user input. Once I replace, I need to output the new madlib. I'm getting the user input into variables, but I'm not sure how to correctly replace the placeholder with the users input.

Current code:

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

Answer Source

Your code should look like

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

You need separate operation for read and write. There are other ways to do this

You can see how to do with single file pointer http://stackoverflow.com/a/10173112/1380263

You can also use ruby methods which interact with shell and use sed command (system, backticks, peopen)

Really depends on what suits your situation the best

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download