Ian's DBC SF Firecrackers Blog

Ruby Class Methods

We've learned a lot about instance methods in Ruby through creating objects from classes and the necessary methods to maintain those objects in the challenges so far in Unit 2. However there's also class methods, methods that are maintained at the class level instead of with each instance, that could perform useful operations, so this gets away from the object-oriented mindset and move more towards functional programming. Let's take a look at an example of a class with class methods:

				class Mathy_Formulae
					def self.pythagorean(a,b)
						Math.sqrt(a**2 + b**2)
					end
					
					def Mathy_Formulae.quad_discriminant(a,b,c)
						b**2 - (4 * a * c)
					end
					
					def Mathy_Formulae.quad_formula(a,b,c)
						d = Mathy_Formulae.quad_discriminant(a,b,c)
						unless d>=0
							raise ArgumentError "No real solutions found"
						end
						[(-b + Math.sqrt(d)) / (2 * a),(-b - Math.sqrt(d)) / (2 * a)]
					end
				end
			

Notice how each method definition either has "self" or the class name "Mathy_Formulae" in front of the method name. Either can be used. If you follow the code, you can see that the methods can be called externally and return the result externally. This is particularly useful for library classes and one such class, Math, is being used here for the square root method.