cgore.comcgore@cgore.commicroblogblogphotosChristianitycryptographyjournalingoutdoorsmy master's thesisprogramming
Thinking Bicycle

Chris Gore: Programming: Ruby: Class Method References from Instance Methods

I commonly define a set of class methods and then specialize them as instance methods in Ruby. Typically in real-life examples, the class method takes one or more arguments and the instance method fills them in with instance variables. How you do this specifically depends on what you want your inheritance to do for that method. As an example:

class A
def f x
self.class.f x
end

def g x
A.g x
end

class << self
def f x
puts "A.f #{x}"
end

def g x
puts "A.g #{x}"
end
end
end

class B < A
class << self
def f x
puts "B.f #{x}"
end

def g x
puts "B.g #{x}"
end
end
end

Calling B.new.f(12)will call B.f, but calling B.new.g(12) will call A.g instead. I always seem to want the inherited classes to have their methods work as in f, but I am sure there are real-life reasons for the second approach.