|
| 1 | +**Note**: \Method +pread+ is different from other reading methods |
| 2 | +in that it does not modify +self+ in any way; |
| 3 | +thus, multiple threads may read safely from the same stream. |
| 4 | + |
| 5 | +Reads up to +maxlen+ bytes from the stream, |
| 6 | +beginning at 0-based byte offset +offset+; |
| 7 | +returns a string containing the read bytes. |
| 8 | + |
| 9 | +The returned string: |
| 10 | + |
| 11 | +- Contains +maxlen+ bytes from the stream, if available; |
| 12 | + otherwise contains all available bytes. |
| 13 | +- Has encoding +Encoding::ASCII_8BIT+. |
| 14 | + |
| 15 | +With only arguments +maxlen+ and +offset+ given, |
| 16 | +returns a new string: |
| 17 | + |
| 18 | + english = 'Hello' # Five 1-byte characters. |
| 19 | + strio = StringIO.new(english) |
| 20 | + strio.pread(3, 0) # => "Hel" |
| 21 | + strio.pread(3, 2) # => "llo" |
| 22 | + strio.pread(0, 0) # => "" |
| 23 | + strio.pread(50, 0) # => "Hello" |
| 24 | + strio.pread(50, 2) # => "llo" |
| 25 | + strio.pread(50, 4) # => "o" |
| 26 | + strio.pread(0, 0).encoding |
| 27 | + # => #<Encoding:BINARY (ASCII-8BIT)> |
| 28 | + |
| 29 | + russian = 'Привет' # Six 2-byte characters. |
| 30 | + strio = StringIO.new(russian) |
| 31 | + strio.pread(50, 0) # All 12 bytes. |
| 32 | + # => "\xD0\x9F\xD1\x80\xD0\xB8\xD0\xB2\xD0\xB5\xD1\x82" |
| 33 | + strio.pread(3, 0) # => "\xD0\x9F\xD1" |
| 34 | + strio.pread(3, 3) # => "\x80\xD0\xB8" |
| 35 | + strio.pread(0, 0).encoding |
| 36 | + # => #<Encoding:BINARY (ASCII-8BIT)> |
| 37 | + |
| 38 | + japanese = 'こんにちは' # Five 3-byte characters. |
| 39 | + strio = StringIO.new(japanese) |
| 40 | + strio.pread(50, 0) # All 15 bytes. |
| 41 | + # => "\xE3\x81\x93\xE3\x82\x93\xE3\x81\xAB\xE3\x81\xA1\xE3\x81\xAF" |
| 42 | + strio.pread(6, 0) # => "\xE3\x81\x93\xE3\x82\x93" |
| 43 | + strio.pread(1, 2) # => "\x93" |
| 44 | + strio.pread(0, 0).encoding |
| 45 | + # => #<Encoding:BINARY (ASCII-8BIT)> |
| 46 | + |
| 47 | +Raises an exception if +offset+ is out-of-range: |
| 48 | + |
| 49 | + strio = StringIO.new(english) |
| 50 | + strio.pread(5, 50) # Raises EOFError: end of file reached |
| 51 | + |
| 52 | +With string argument +out_string+ given: |
| 53 | + |
| 54 | +- Reads as above. |
| 55 | +- Overwrites the content of +out_string+ with the read bytes. |
| 56 | + |
| 57 | +Examples: |
| 58 | + |
| 59 | + out_string = 'Will be overwritten' |
| 60 | + out_string.encoding # => #<Encoding:UTF-8> |
| 61 | + result = StringIO.new(english).pread(50, 0, out_string) |
| 62 | + result.__id__ == out_string.__id__ # => true |
| 63 | + out_string # => "Hello" |
| 64 | + out_string.encoding # => #<Encoding:BINARY (ASCII-8BIT)> |
| 65 | + |
0 commit comments