Natela Natela - 2 years ago 64
Ruby Question

Converting file to string and replacing string text with user input

I need to replace placeholders

, and
in a file
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 ="solution09.txt", "r")
contents =
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)

Answer Source

Your code should look like

filename = "solution09.txt"

puts "Enter a noun: "

puts "Enter a verb: "

puts "Enter an adjective: "

puts "Enter an adverb: "

if contents.include?('NOUN')
  { "\[NOUN\]" => noun,
    "\[VERB\]" => verb,
    "\[ADJ\]" => adj,
    "\[ADV\]" => adv
  }.each do |key, value|
    contents.gsub!(key, value)
  end, "w") { |f| f << contents }

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

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