Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

IO.binread

IO.binread(name, [length [, offset]]) → string
File.binread(name, [length [, offset]]) → string

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). binread ensures the file is closed before returning. The open mode would be "rb:ASCII-8BIT".

If name starts with a pipe character ("|") and the receiver is the IO class, a subprocess is created in the same way as Kernel#open, and its output is returned. Consider to use File.binread to disable the behavior of subprocess invocation.

Example
File.binread("testfile")           #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
File.binread("testfile", 20)       #=> "This is line one\nThi"
File.binread("testfile", 20, 10)   #=> "ne one\nThis is line "
IO.binread("| cat testfile")       #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"

See also IO.read for details about name and open_args.

See also .binwrite .console also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0