2012-12-15 25 views
2

這是我正在運行的代碼,直到第15行才能正常運行。我運行的命令是:ruby ex16.rb text.txt。這是一個實踐樣本我寫這意味着是一個簡單的小的文本編輯器:未定義的方法大小爲#<File:text.txt>(NoMethodError)

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!" 
target.truncate(target.size) 

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()undefined method 'size' 

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() 
+0

您使用的是什麼版本的Ruby,以及在什麼平臺上?如果你想擦除文件內容,爲什麼不只是做target.truncate(0)? –

+0

在1.8.6中出現同樣錯誤,在1.9.2中工作。奇怪,因爲鎬1.8對File.size沒有特別的說明。 – BernardK

+0

迭戈 - 這是一個練習練習,我被要求寫。 – matthewp

回答

4

size行爲已更改版本之間!這是1.8中的類方法,1.9中的類和實例方法。

print '-----File.instance_methods'; p File.instance_methods.sort.grep(/^si/) 
print '-----File.singleton_methods'; p File.singleton_methods.sort.grep(/^si/) 

case RUBY_VERSION 
when '1.8.6' 
    puts '1.8.6 '; p File.size('t.rb') 
when '1.9.2' 
    puts '1.9.2 '; p File.open('t.rb').size 
    puts '1.9.2 '; p File.size('t.rb') 
else 
    puts 'not for this version' 
end 

$ ruby -v 
ruby 1.8.6 (2010-09-02 patchlevel 420) [i686-darwin12.2.0] 
$ ruby -w t.rb 
-----File.instance_methods["singleton_methods"] 
-----File.singleton_methods["size", "size?"] 
1.8.6 
334 


$ ruby -v 
ruby 1.9.2p320 (2012-04-20 revision 35421) [x86_64-darwin12.2.0] 
$ ruby -w t.rb 
-----File.instance_methods[:singleton_class, :singleton_methods, :size] 
-----File.singleton_methods[:size, :size?] 
1.9.2 
334 
1.9.2 
376 

PS:有人下來投了你的問題,可能是因爲它太長。下次只發布錯誤的行,以及需要理解該行的問題。

+0

感謝您的幫助,伯納德以及對此投票的解釋。下次會做得更好。乾杯。 – matthewp

相關問題