# -*- ruby -*- # hello world # print a simple string on stdout puts "Hello World" # argv # access command line parameters (no segmentation fault accepted, nor silent exception, so some languages must explicitly check the presence of the argument) puts ARGV[0] # env # access environment variable puts ENV["HOME"] # test file exists # return exit code error (non zero) if a file does not exist test ?e, "/etc/mtab" or exit 1 # test file readable # return exit code error (non zero) if a file is not readable test ?r, "/etc/mtab" or exit 1 # formatting # print integers in a simple formatted string a=1; b=2; puts "#{a} + #{b} = #{a + b}" # system # call an external program and check the return value system "false" or $stderr.puts "false failed"; system "echo done" # sed in place # remove #-comments from a file (modifying the file, i.e. in place) % ruby -pi -e '$_.sub!(/#.*/, "")' # compile what must be # find and compile .c files into .o when the .o is old or absent Dir['**/*.c'].each{|c| o = c.sub('.c$', '.o') if test ?>, c, o then puts "compiling #{c} to #{o}" system("gcc", "-c", "-o", o, c) end } # grep # grep with -F -i -h handling, usage, grep'ing many files require 'getopts' getopts('Fih') ARGV.empty? || $OPT_h and (puts "usage: grep [-F] [-i] regexp [files...]"; exit 1) r = ARGV.shift r = Regexp.quote(r) if $OPT_F r = /#{r}/i if $OPT_i prefix = ARGV.size > 1 while gets print prefix ? "#{ARGF}:" : '', $_ if $_ =~ /#{r}/ end