Hi All,
SCENARIO: I took an example from Ruby Cookbook which had a private method 'secret'. 'secret' returned the value of @secret initialized to a random value.
I created a subclass whose initializer called super and accessed secret to save its returned-value in a instance variable, which I then displayed. It matched the value I dumped when the parent class was initialized. Success!
However, I tried a alternative approach, which failed --- which is my reason for posting this.
I created a public method 'spy' in the parent class and returned the value @secret, just like the private method 'secret' did. I then invoked spy from a subclass instance, but it returned nil.
QUESTION: Why does subclass.spy return nil?
Code follows.
Thanks in Advance, Richard
=========== SecretNumber.rb ==================== # Source: Ruby Cookbook, p. 371-373
class SecretNum def initialize @secret=rand(20) puts "@secret <= #{@secret}" end
def hint puts "The number is #{"not " if secret<10}greater than 10" end
private def secret @secret end
public def spy @secret end attr_reader :spy end
=========== SecretNumber_AccessInSubclass.rb =================== # SecretNumber_AccessInSubclass.rb
require 'SecretNumber.rb'
class NotSoSecretNum < SecretNum def initialize super @theNum = secret end
attr_reader :theNum
end
s = NotSoSecretNum.new puts "theNum reveals \"secret\" = " + s.theNum.to_s puts "secret reveals \"secret\" = " + "\"s.secret\" not accessible" puts "spy reveals \"secret\" = " + s.spy.inspect.to_s
========= Results ============== @secret <= 3 theNum reveals "secret" = 3 secret reveals "secret" = "s.secret" not accessible spy reveals "secret" = nil