Kernel#test

test(mode, file1 [, file2]) -> boolean or integer
Returns: Boolean or Integer · Updated March 13, 2026 · Kernel Methods
files testing permissions filesystem

The test method checks file characteristics using single-character operators. It’s Ruby’s direct access to file test operations similar to Perl’s -e, -f, etc.

File Test Operators

Basic Checks

# -e: File exists
test(?e, "file.txt")   # => true/false
File.exist?("file.txt") # Equivalent

# -f: Regular file
test(?f, "file.txt")

# -d: Directory
test(?d, "/path")

# -l: Symbolic link
test(?l, "link")

Permission Tests

# -r: Readable
test(?r, "file.txt")

# -w: Writable  
test(?w, "file.txt")

# -x: Executable
test(?x, "script.rb")

Type Tests

# -b: Block device
# -c: Character device
# -p: Named pipe
# -S: Socket
test(?b, "/dev/sda")
test(?c, "/dev/tty")
test(?p, "/tmp/fifo")
test(?S, "/tmp/socket")

Binary Operators (Two Arguments)

Compare Files

# =: Same file (inode)
test(?=, "file1.txt", "file2.txt")

# -N: Newer than
test(?N, "new.txt", "old.txt")

# -O: Owned by current process
test(?O, "file.txt")

# -G: Group matches current process
test(?G, "file.txt")

Practical Examples

File Existence Check

def ensure_file_exists(path)
  unless test(?e, path)
    File.write(path, "")
    puts "Created: #{path}"
  end
end

Permission Checking

def run_script?(path)
  test(?e, path) && test(?x, path)
end

# Usage
puts run_script?("deploy.sh")  # true if exists and executable

Safe File Operations

def read_if_exists(path)
  return nil unless test(?f, path) && test(?r, path)
  File.read(path)
end

Directory Creation

def ensure_directory(path)
  return true if test(?d, path)
  Dir.mkdir(path)
end

Block Device Detection

# Check for devices
def device?(path)
  test(?b, path) || test(?c, path)
end

device?("/dev/null")    # => true
device?("/dev/zero")    # => true
device?("/dev/sda")    # => true (block)

StringShortcut Form

# Can also use character directly
?e  # => "e"
test(?e, "file")  # Same as test("e", "file")

Ruby 3.0+ Modern Alternative

# Modern methods preferred
File.exist?(path)
File.readable?(path)
File.executable?(path)
File.directory?(path)

While test is powerful and concise, modern Ruby code typically uses the more readable File. methods. The test method remains useful for scripting and when you need compact file tests.

See Also