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)
return(a+b)
end
end
myObject=MyClass.new
print myObject.sum(1,4)
class MyClass
def product(a,b)
return (a*b)
end
end
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