Getting A File’s Information In Ruby Using File::Stat

Here’s another nice tip from Michael Morin on how to get a file’s information in Ruby using the File::Stat class; information such as such as file size, date last modified, date last accessed, and more. This can be quite useful in situations wherein you want to query the operating system about a particular file without having to open it.

ScreenHunter 618 Oct. 12 10.19 Getting A File’s Information In Ruby Using File::Stat

An example scenario would be like this: a program has to iterate over the files in a directory and determine the files sizes and the total size. Plus, it must work recursively, totaling the file sizes of all the files in all subdirectories of the current directory. To be able to achieve this task, we use the find library included with Ruby.

#!/usr/bin/env ruby
require "find"
files = []
total = 0
Find.find('.') do|f|
 files << f
 total += File.stat(f).size
end
puts "There are #{files.length} files"
puts "They are %0.2f megabytes in size" % (total / 1024.0 / 1024.0)

Incoming search terms for the article:

Related Posts

Create Google Play’s Tab Navigation Using jQuery And CSS

PS Advanced Compositioning

How To Create A Triangular Pixelation Effect Using Photoshop

How to Create Subtle Caption Hover Effects