My First Ruby Program

Posted by Christopher Smith Sat, 09 Sep 2006 22:43:00 GMT

I realized that earlier today I wrote my first Ruby program, and it’s probably worth documenting this moment for posterity.

It’s a trivial bit of code:

Fixing Typo sequence numbers
require 'postgres'

sequences = [
  'blacklist_patterns', 'blogs', 'categories',
  'contents', 'page_caches', 'pings',
  'redirects', 'resources', 'sessions',
  'sidebars', 'tags', 'text_filters',
  'triggers', 'users'
]

def fixSequence(db,tableName)
  results = db.query("select max(id) from #{tableName}")
  max_id = results.first.first
  if max_id then 
    db.exec("select setval('#{tableName}_id_seq'::text,#{max_id});").clear
  end
end

db = PGconn.connect("localhost", 5432)
sequences.each {|sequence| fixSequence(db,sequence)}
db.close()

So far, my first impression is that Ruby tries to be like Smalltalk, but is Perlish enough to fall short IMHO. Of course, I hardly know the language yet, so there may be a more elegant way to do things that I have yet to uncover. In particular, I’m wondering why the True and False classes don’t have “ifTrue:ifFalse” type methods that take blocks as arugments. Seems like an obvious “nice to have”. IIRC it’s possible to add methods to existing classes, so maybe I can do this to keep the Smalltalk cravings to a minimum.