2014-02-08 61 views
2

此代码:相同的字符串但不相等 - 发生了什么?

io = StringIO.new "\xAF" 
puts "\xAF".unpack('C') 
puts (io.read 1).unpack('C') 
puts 'Unequal' if io.read(1) != "\xAF" 

打印:

175 
175 
Unequal 

为什么当通过StringIO传递是两个字符串不相等?显然,它们都对应于175的值,但不知何故它们不相等。

+0

io'两次。第二次读取返回nil。 –

回答

3

文件对象(包括StringIO)有一个文件指针。一旦文件被读取/写入,文件指针就会前进。

io = StringIO.new "\xAF" 
io.read(1) 
# => "\xAF" 
io.read(1) # File pointer advance. reached EOF. No more character. 
# => nil 

如果你想重新阅读的字符,请使用seek方法:你是从'读

io.seek(0) # Move to offset 0 
io.read(1) 
# => "\xAF" 
+0

是的。确实是这样..你打我2秒 –

+0

叹息..我完全忘了!当然。多谢你们! – johnrl

相关问题