Ruby - Get a File Size

1. Introduction

Knowing the size of a file can be crucial in many applications, especially when managing storage, uploading, or downloading files. Ruby simplifies this task with the File class, which provides methods to fetch the size of a given file. In this article, we will discuss how to determine the size of a file using Ruby.

Getting the file size means retrieving the amount of storage space a file occupies on the disk. It's commonly measured in bytes, but for user-friendly output, it might be converted to larger units like kilobytes (KB), megabytes (MB), etc.

2. Program Steps

1. Load the required library/module.

2. Specify the file name/path for which the size needs to be checked.

3. Use the size method from the File class to obtain the file size in bytes.

4. Print the result.

3. Code Program

# Specify the file name/path for which the size needs to be checked
file_name = "sample.txt"
# Check if the file exists
if File.exist?(file_name)
  # Get the file size in bytes
  file_size = File.size(file_name)
  puts "The size of the file '#{file_name}' is #{file_size} bytes."
else
  puts "The file '#{file_name}' does not exist!"
end

Output:

The size of the file 'sample.txt' is 1024 bytes.
Or
The file 'sample.txt' does not exist!

Explanation:

1. file_name = "sample.txt": Here, we specify the name or path of the file for which we want to determine the size.

2. File.exist?(file_name): Before attempting to get the size, we first check if the file exists to avoid any errors.

3. File.size(file_name): The size method from the File class returns the size of the file in bytes.

4. Depending on whether the file exists or not, an appropriate message is printed out, either displaying the file's size or indicating that the file doesn't exist.


Comments