get system free disk space in ruby

You can get the system free disk space in Ruby by executing a command line instruction using the system method and reading the output. In this case, we will be using the df command to get the disk space information and the -k and -h options to display the output in a human-readable format. Here's an example code block:

main.rb
# Execute the command and store the output in a variable
output = `df -kh`

# Split the output into an array of lines
lines = output.split("\n")

# Get the last line, which has the information for the root directory where the script is executing
root_dir_line = lines.last

# Split the line into an array of fields
fields = root_dir_line.split(" ")

# Get the fourth field, which has the amount of available disk space in bytes
available_bytes = fields[3].to_i * 1024

# Convert the amount of bytes to a human-readable format
require 'filesize'
available_space = Filesize.from(available_bytes.to_s + " B").pretty

# Print the result
puts "Available disk space: #{available_space}"
681 chars
22 lines

Note that this code gets the available disk space for the root directory where the Ruby script is executing, but you can modify it to get the information for any directory by passing the directory path as a parameter to the df command.

gistlibby LogSnag