cgore.comcgore@cgore.commicroblogblogphotosChristianitycryptographyjournalingoutdoorsmy master's thesisprogramming
Thinking Bicycle
Github @cgoreFacebook @cgoreInstagram @christopher.mark.gore

This website is copyright © 1995-2016 Christopher Mark Gore, all rights reserved. The content may not be copied or republished via any means, traditional or electronic, without express written permission of the author.

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.