سؤال

Is there any similar peek(); (From C++) function in ruby? Any alternative to do this?

I've found a way to do this.

Use the StringScanner:

require 'strscan'
scanner = StringScanner.new(YourStringHere)
puts scanner.peek(1)

You can use the StringScanner to scan files as well:

file = File.open('hello.txt', 'rb')
scanner = StringScanner.new(file.read)
هل كانت مفيدة؟

المحلول

Maybe you can use ungetc. Try to look here.

It is not equal but you can obtain the same result.

نصائح أخرى

Enumerator#peek let's you peek at the next value of an Enumerator. IO#bytes IO#chars will give you an Enumerator on a byte stream or character stream respectively. Since you opened with "rb", I'll assume you want bytes.

file = File.open('hello.txt', 'rb') # assume contains text "hello\n"
fstream = file.bytes

fstream.next # => "h"
fstream.peek # => "e"
fstream.next # => "e"
...

Of course now you're kinda stuck with byte at a time processing on the stream.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top