-1

I have the following code, which hangs up on writing user input to a file. What is my error here?

file=File.open("Debsfile.txt", "r+") do |file|
  file.puts "This is Deb's file. It's a great file. It has many characters, words and lines."
  file.puts "This is another line of text in Deb's file."
end
  puts "What is your favorite color?"
  color = gets
  color = color.chomp
  color.write
file.close

File.open("Debsfile.txt").readlines.each do |line|
  puts line
end
dijit
  • 1
  • 3

2 Answers2

2

If I run the program as yours, the error message is:

undefined method `write' for "red":String (NoMethodError)

The problem is you are calling write method on color which is a string object. You actually wanted to write the input color to the file, so, you need to call write method on a File (or IO object): file.write color like following:

File.open("Debsfile.txt", "r+") do |file|
  file.puts "This is Deb's file. It's a great file. It has many characters, words and lines."
  file.puts "This is another line of text in Deb's file."
  puts "What is your favorite color?"
  color = gets
  color = color.chomp  
  file.write color  # writing the color to the file here
end

File.open("Debsfile.txt").readlines.each do |line|
  puts line
end

See this post for the details on how to write to file in Ruby.

Community
  • 1
  • 1
K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
0
file=File.open("Debsfile.txt", "a+") do |file|

adds two lines of text to the file

file.puts "This is Deb's file. It's a great file. It has many characters, words and lines."
file.puts "This is another line of text in Deb's file."
#asks user for favorite color in console
puts "What is your favorite color?"
#assigns color to variable "color"
color = gets
#color.chomp cuts of the new line character so that you just have the user input
color = color.chomp
#adds the color to the end of the file
file.puts("Your favorite color is #{color}.") #writing the color to the file

end #end of file open

File.open("Debsfile.txt").readlines.each do |line| puts line end

dijit
  • 1
  • 3