문제

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