Search code examples
ruby-on-railsrubysuperclass

Ruby call child method from parent class


I'm writing a program in rails where one class has the same behavior as another class. The only difference is that there is a class variable, @secret_num, that is calculated differently between the two classes. I would like to call a particular super class method, but use the class variable from the child class. What is tricky is that the class variable is not a constant so I am setting it within its own method. Is there any way to do what I'm attempting to do below? Thanks

Class Foo
  def secret
    return [1,2,3].sample
  end

  def b
    @secret_num = secret
    ... # lots of lines of code that use @secret_num
  end
end

Class Bar < Foo
  def secret
    return [4, 5, 6].sample
  end

  def b
    super    # use @secret_num from class Bar.
  end
end    

This doesn't work because the call to super also called the parent class's secret method, i.e. Foo#secret, but I need to use the secret number from the child class, i.e. Bar#secret.


Solution

  • class Foo
      def secret
        [1,2,3].sample
      end
    
      def b(secret_num = secret)
        <lots of lines of code that use secret_num>
      end
    end
    
    class Bar < Foo
      def secret
        [4, 5, 6].sample
      end
    end    
    

    Note, you don't need to pass secret as an argument to b. As long as you don't redefine b in the subclass, inheritance will take care of calling the correct implementation of secret.

    My preference is to have it as an argument so I can pass in various values in testing.