2

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)
  • 1
    For those unfamiliar with C++, `peek` returns the next character without consuming input. – Pubby Apr 07 '12 at 03:17

2 Answers2

2

Maybe you can use ungetc. Try to look here.

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

dash1e
  • 7,677
  • 1
  • 30
  • 35
1

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.

dbenhur
  • 20,008
  • 4
  • 48
  • 45