Strange variable scopes – Class variables (part 1)

There we go again. Ruby has some, err… “unique” features when to the scope of variables. It really starts out really harmless, though…

This is part one of two – this one is just to give you a bit of background for the next one. There’s not much surprising stuff there, so if you want to go for the stranger bits, just jump to the next installment.

More methods at runtime

As I expected, I missed some stuff in my last post about adding methods at runtime. One thing is that the idiom for adding class methods is “class < < self" rather than "class << Classname"

More importantly, if you define things like I did in my last post, you will not be able to use variables in the method definition. The things after "class << self" are executed in a different scope that doesn't inherit the variables from the surrounding code.

Fortunately, Ola Bini has a post that explains some of these things in more detail. Obviously, the idiom for creating class methods at runtime uses a combination of “module_eval” and “define_method”:

Continue reading “More methods at runtime”

Adding methods at runtime

One of the things that seems to draw people to Ruby is the ability to create and change all things at metprogrammatically at runtime. This in turn allows users to create things like domain-specific languages and the like.

I’m possibly overusing these features at the moment, because it’s a cool new thing ™.

So, let’s see how to add methods at runtime. Since this is Ruby, there are multiple ways to do this, making things more confusing.

(See also the follow-up article)

Blog at

Up ↑

%d bloggers like this: