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.
Note, you don’t need to pass
secretas an argument tob. As long as you don’t redefinebin the subclass, inheritance will take care of calling the correct implementation ofsecret.My preference is to have it as an argument so I can pass in various values in testing.