Ruby (sans Rails)

Fair warning_ If you aren't programatically inclined, you may want to skip this post.

(Yes, "programatically" is a word, because I say so.)

I wasted a few minutes tonight trying to find out what was wrong with this simple piece of ruby code (which is part of a GEO parser, for the curious)

infile.each_line {|line|
    if (line=~/\^SAMPLE = (.+)/)
        newFile ="#.soft", "w")

    elsif (line=~/!sample_table_begin/)
        header = false
        data = true

    elsif (line=~/!sample_table_end/)
        data = false

    elsif (data == true) && (fileopen = true)
        newFile.print line

it kept giving me the error_

open private method `print' called for nil_NilClass

Turns out it was a trivial scope problem. In Ruby, variables declared within the loop don't persist into the next iteration of the loop. Contrast this with perl, where doing that would work just fine. Perhaps the perl way is fundamentally sloppier, but it's a heck of a lot more convenient.

I should have caught this sooner, but switching languages has been messing with my head. Most of our lab uses Ruby, and I've been slowly weaning myself off of perl and converting my scripts over.

My biggest complaint so far is that being a young language, Ruby lacks the resources of a Java or a Perl. It's easy to find a Perl resource to answer your question, but Ruby forums are less common (The Pragmatic Programmer's Guide rocks, though). The same goes doubly for packages. I looked for ages and couldn't find a single goddamn Ruby package that will do a student's t-test. It ended up being easier to use RSruby to interface with my R-server, which is kind of a ridiculous work-around, when you think about it.

All things considered, though, Ruby's not a bad language. It's similar enough to perl that switching wasn't horrible, and I've found that the syntax is much cleaner and much more intuitive. Writing code is faster when you don't have to screw around with dollar signs and semicolons all the time.

Oh, and for the curious, prefixing all of my 'newFile's with @ to make them instance variables fixed the problem. Declaring newFile outside of the loop would have also worked.


comments powered by Disqus