Ruby file example

Simple Ruby example handling script arguments and files. All text files in a specified folder is printed with line numbers.

#!/usr/bin/env ruby

# Print all text files in specified folder (with line numbers)
def print_files(folder)
  Dir.entries(folder).each do |name|
    if File.extname(name) =~ /.rb|.txt|.sh|.tex|.lyx|.xml|.html|.htm|.md/
      puts
      puts "File: " + name
      File.open(name, "r") do |infile|
        counter = 1
        while (line = infile.gets)
          puts "#{counter}: #{line}"
          counter += 1
        end
      end
    end
  end
end

if (ARGV.size == 1) 
  print_files(ARGV[0])
else 
  puts "Usage: ./print_files.rb <folder> (e.g. ./print_files.rb .)"
end

References