Ask A Question

Notifications

You’re not receiving notifications from this thread.

Inheritance is not working.

leroydupuis asked in Ruby

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?

Reply

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.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,464+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.