Similar function peek( ); (from C++) in Ruby
Question
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)
Solution
Maybe you can use ungetc
. Try to look here.
It is not equal but you can obtain the same result.
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow