2014-04-28 48 views
0

Ruby中的新手和一般编程。Ruby - '读取':无法将字符串转换为整数

我想写入一个文件,然后打印我写到终端中的文件。

filename = ARGV.first 
script = $0 

puts "Would you like to read the file?" 
puts "If you want to, hit RETURN." 
puts "If you don't want to, hit CTRL+C." 

prompt = "? " 
STDIN.gets 

puts "Opening file..." 
target = File.open(filename, 'w+') 

puts "Reading file..." 
puts target.read() 

puts "Blank, huh?" 

print "Write something: "; line1 = STDIN.gets() 
print "A little more: "; line2 = STDIN.gets() 

target.write(line1) 
target.write(line2) 

puts "Let's read it now." 
puts target.read() 

的代码运行,直到我到最后一行,此时下面的错误被抛出:

exl16_2.rb:26:in `read': can't convert String into Integer (TypeError) 
    from exl16_2.rb:26:in `<main>' 

不知道这意味着什么的什么,我试图做上下文(内打印出所写的内容)。

回答

0

不确定是什么原因导致您的错误,您使用的是什么Ruby版本?我试过w/1.9和2.1,但没有得到。然而,有你的代码的问题,试试这个:

filename = ARGV.first 
script = $0 

puts "Would you like to read the file?" 
puts "If you want to, hit RETURN." 
puts "If you don't want to, hit CTRL+C." 

prompt = "? " 
STDIN.gets 

puts "Opening file..." 
target = File.open(filename, 'w+') 

puts "Reading file..." 
puts target.read() 

puts "Blank, huh?" 

print "Write something: "; line1 = STDIN.gets() 
print "A little more: "; line2 = STDIN.gets() 

target.write(line1) 
target.write(line2) 
target.rewind() 

puts "Let's read it now." 
puts target.read() 

如果你从你写后,读取该文件,它会显示为空。调用rewind将确保您正在从文件的开头读取数据。

+0

我正在运行1.9.3。倒带完美地工作,感谢您的帮助。 – Cat

相关问题