I'm brand new to programming and I'm working on Learn Ruby The Hard Way. In Exercise 15 he shows how to open and read a text file, and how to print that to the screen. In the next exercise, he briefly mentions at the beginning that the '.read' command "Reads the contents of a file. You can assign the result to a variable."
All I want to know is HOW to assign the result of a read to a new variable. In exercise 16 he doesn't use it and just keeps going into writing. I wrote a short script to read a text file containing a number, then '.to_i' that number and return a boolean value. I know I'm missing something, and it doesn't add up to me.
Basically all I need to know is how to assign the txt.read output to a new variable (simply called, 'variable') and then use gets.chomp.to_i to convert it to an integer so the boolean comparison works. Any help is appreciated, thank you!
print "Enter the filename: "
filename = gets.chomp
txt = open(filename)
print txt.read
variable = txt.read.to_i ##Trying to assign the txt.read to a variable?
print { variable > 4 && false }
When opening a file a cursor is created to the point in that file we have read to. Calling
readwithout any extra arguments reads the whole file and points that cursor to the end of the file, so any subsequentreadcalls will return an empty string (""). In your case you would need to assign first and then do anything else:You can compare this with calling
readmany times with an argument signifying the number of bytes to read. You will get another chunk of the file of the specified length each time.Also your final call is probably problematic - print does not take a block and that's what you're passing. You just need to
print(variable > 4)or something similar.