All Geek to Me

July 25, 2009

A Bottle of Tequila and a Loaded Gun

Filed under: Geek Stuff — britinla @ 8:29 am

I am learning to code in Ruby. Ruby is an interpreted object orientated programming language with some powerful features.

For instance, variables are dynamically typed as illustrated by the following snippet of code:

myVar = 4
print myVar.class
myVar = “Four”
print myVar.class

This code will print Fixnum and then String, indicating that the variable changed class depending on the assigned value.

Classes are never closed, you can add methods to them at any point.

class MyClass
    def sum(a,b)
print myObject.sum(1,4)

class MyClass
    def product(a,b)
        return (a*b)

print myObject.product(2,4)

This code will print 5 and then 8

myObject is created from MyClass at a point at which the only method in the class is sum. A new method is added to the class and the existing object is able to to use that method even though it did not exist at the time of its creation.

Even system classes can have methods added or overridden. Changing the behaviour of existing classes, known as Monkey Patching, is an interesting, but very dangerous technique; like the bottle of tequila and loaded gun of this post’s title. It can be useful if it adds functionality to existing classes, providing a string comparison that returns a number expressing a percentage confidence that two strings were intended to be equal. This allows the user to key Califonia and for the program to accept that this was probably intended to be California. It can also be used to change existing methods in classes; having the equality comparison return true for 2+2=5 is only useful in the world of 1984, but being able to fix a problem in a supplied Ruby library is clearly invaluable.

With Great Power comes Great Responsibility


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at

%d bloggers like this: