Docunext


Ruby Classes Modules Objects and Blocks

November 22nd, 2009

I've just written up some notes on running Sinatra on Debian over at Docunext.

While I finally got some Rack middleware operational between my Sinatra application and the Thin webserver, it took me too long to figure it out.

I obviously need to get a better understanding of Ruby Classes, Modules, Objects and Blocks!

Here's a class:

class Rclass
    def initialize()
        @barf = "hi"
    end
    def run()
        puts @barf
    end
end
bb = Rclass.new()
bb.run()

OK, so that's a class, and with it we can create an object instance ("bb").

What is a Ruby module? As I understand it, its where programming Ruby becomes much more Ruby-esque than other programming languages.

Thankfully, Ruby Fleebie has a nice tutorial on modules and mixins. I've read it before, and its time for a review.

Right - modules without the mixin capability is just an easy way to organize the different parts of a larger software program. Also noteworthy, it is possible to create classes within modules, like so:

module BarfModule
    class BarfClass
        #...
    end
end

Reminiscent of perl, modules use the double colon syntax ("::") to reference module-specific code.

Aha, now I remember why the tutorial from Ruby Fleebie didn't really sink in. The explanation of module mixins in part II is confusing to me.

Let me try to find another tutorial and figure it out more clearly. This one does the trick:

This article is also helpful:

NOTE: Yehuda's favotire thing #5 is the approach I took when creating Aortica, a web application framework written in Perl. Its a cool notion: code that writes new code as it runs, then runs the new code it has written as appropriate. Nice, huh?

Yearly Indexes: 2003 2004 2006 2007 2008 2009 2010 2011 2012 2013 2015 2019 2020 2022