I am doing an exercise in a tutorial, which is to get this code to run:
1 filename = ARGV.first
2 script = $0
3
4 puts “We’re going to erase #{filename}.”
5 puts “If you don’t want that, hit CTRL-C (^C).”
6 puts “If you do want that, hit RETURN.”
7
8 print "? "
9 STDIN.gets
10
11 puts “Opening the file…”
12 target = File.open(filename, ‘w’)
13
14 puts “Truncating the file. Goodbye!”
15 target.truncate(target.size)
16
17 puts “Now I’m going to ask you for three lines.”
18
19 print “line 1: “; line1 = STDIN.gets.chomp()
20 print “line 2: “; line2 = STDIN.gets.chomp()
21 print “line 3: “; line3 = STDIN.gets.chomp()
22
23 puts “I’m going to write these to the file.”
24
25 target.write(line1)
26 target.write(”\n”)
27 target.write(line2)
28 target.write(”\n”)
29 target.write(line3)
30 target.write(”\n”)
31
32 puts “And finally, we close it.”
33 target.close()
when I tried to run the above I got a No Method Error for size on line
15.
After some experimentation I got the following to run apparently as
expected:
filename = ARGV.first
script = $0
puts “We’re going to erase #{filename}.”
puts “If you don’t want that, hit CTRL-C (^C).”
puts “If you do want that, hit RETURN.”
print "? "
STDIN.gets
puts “Opening the file…”
target = File.open(filename, ‘w’)
puts “Truncating the file. Goodbye!”
flength=File.size(target)
target.truncate(flength)
puts “Now I’m going to ask you for three lines.”
print "line 1: "; line1 = STDIN.gets.chomp()
print "line 2: "; line2 = STDIN.gets.chomp()
print "line 3: "; line3 = STDIN.gets.chomp()
puts “I’m going to write these to the file.”
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
puts “And finally, we close it.”
target.close()
So why does the file with my change work? Or, if you prefer, why did the
original give a NoMethodError?