An Introduction to Scripting in Ruby
Real life has had me far to busy to post for quite some time. I hope to get back to updating posts more in the future but I promise nothing.
Just for fun, here’s a ruby version of the code; It doesn’t have all of the frills of the others but performs roughly the same function. I don’t have time to make it pretty.
You’ll see an example of exception handling, sorting a hash by value, reading a file into an array, etc. The net result is a script that does the same thing my other scripts do but this time it’s in Ruby. I’m building a little Rosetta Stone.
#!/usr/bin/ruby
require 'resolv'
# arrays and hashes need to be initialized in ruby
accessLog = []
# set hash values to default of 0 or you can't +=
addresses = Hash.new(0)
# read in the file
accessLog = File.readlines('/var/log/httpd/access_log')
# take the first word from each line of the file
accessLog.each { |line| addresses[line.split[0]] += 1 }
# sort hash by value
addresses = addresses.to_a.sort_by {|a,b| b}
# print each of the keys and values, make them pretty
addresses.each do |key, value|
# error handling, the resolv often fails
begin
puts value.to_s.ljust(10) + Resolv.new.getname(key)
rescue
puts value.to_s.ljust(10) + key
end
end

