Skip to main content

Inheritance is not working.

Ruby • Asked by leroydupuis

Hi,

I'm a starter in ruby, I have a doubt in Inheritance in ruby. This is my sample code.

class TimeLine
    attr_reader :tweets
    def initialize(tweets=[])
        @tweets = tweets
    end
    def print
        puts tweets.join("\n")
    end
end

class AuthenticateTimeLine < TimeLine
    def print
        authenticate!
        super
    end
    def authenticate!
        puts "authenticated!"
    end
end
TimeLine.new([1,2,3,4])
authenticate_timeline = AuthenticateTimeLine.new
authenticate_timeline.print

In my code I'm getting a empty array when calling from the child class.Why is that happening?


Hey leroydupuis,

To get the result you're after, remove TimeLine.new([1,2,3,4]) and instantiate AuthenticateTimeLine with the array instead

authenticate_timeline = AuthenticateTimeLine.new([1,2,3,4])
authenticate_timeline.print

You don't create the parent object and then create the child object, the child object inherits from the parent object so you just work from the child. There are way better / more scholarly explanations for all this than what I can regurgitate, just Google ruby inheritance and keep playing around with it, you're 99% there.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.