2

这是我正在运行的代码,它运行良好,直到我到达第 15 行。我运行的命令是:ruby ex16.rb text.txt. 这是我正在编写的一个练习示例,它旨在成为一个简单的小文本编辑器:

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()
4

1 回答 1

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:有人否决了您的问题,可能是因为它太长了。下次只发布错误的行和理解有问题的行所必需的行。

于 2012-12-15T21:43:46.270 回答