Bird
Raised Fist0
RubyHow-ToBeginner · 3 min read

How to Get File Size in Ruby: Simple Syntax and Examples

In Ruby, you can get the size of a file using the File.size method by passing the file path as an argument. This method returns the file size in bytes as an integer.
📐

Syntax

The basic syntax to get a file size in Ruby is:

  • File.size(path): Returns the size of the file at path in bytes.

Here, path is a string representing the file's location on your system.

ruby
File.size("path/to/your/file.txt")
💻

Example

This example shows how to get the size of a file named example.txt and print it in bytes.

ruby
file_path = "example.txt"
size = File.size(file_path)
puts "The size of '#{file_path}' is #{size} bytes."
Output
The size of 'example.txt' is 1234 bytes.
⚠️

Common Pitfalls

Common mistakes when getting file size include:

  • Using a wrong or non-existent file path, which raises an Errno::ENOENT error.
  • Trying to get size of a directory instead of a file, which may raise an error or give unexpected results.
  • Not handling exceptions when the file is missing or inaccessible.

Always ensure the file exists and handle errors gracefully.

ruby
begin
  size = File.size("missing_file.txt")
  puts "Size: #{size} bytes"
rescue Errno::ENOENT
  puts "File not found. Please check the path."
end
Output
File not found. Please check the path.
📊

Quick Reference

Summary tips for getting file size in Ruby:

  • Use File.size(path) to get size in bytes.
  • Ensure the file path is correct and accessible.
  • Handle exceptions for missing files.
  • File size is returned as an integer representing bytes.
✅

Key Takeaways

Use File.size(path) to get the file size in bytes in Ruby.
Always verify the file path exists to avoid errors.
Handle exceptions like Errno::ENOENT for missing files.
File.size returns an integer representing the size in bytes.