Problem with inheritance and classes in Ruby

Asked

Viewed 21 times

0

I have this code. I cannot print the editor variable in the incrementNameTitle method, it is not being displayed. The result is as follows:

Publisher: In Flames - Collins!

class Editora 
   attr_accessor :nameEditora
   def initialize(nameEditora)
      @nameEditora = nameEditora
   end
   def incrementNameTitle
      puts "Editora #{@nameEditora}: #{@title} - #{@author}!"
   end
end
   
class Book < Editora
   attr_accessor :title, :author
   def initialize(title, author)
      @title = title
      @author = author
   end
end

book = Book.new("Em Chamas", "Collins")
editora = Editora.new('LucasLivros')

puts book.incrementNameTitle
  • You urged the classes separately, so why use inheritance? A book is a publishing house?

  • Um, I’m learning POO so I didn’t get your comment right. How can I access the variables title and Author in the Book class?

  • Inheritance should be used to create subtypes, or a specialization of an abstraction. In doing Book inherit from Editora You’re basically defining a book as a subtype of a publishing house. That doesn’t make sense. Perhaps what would make more sense there is composition - and who knows you can read more deeply about it.

  • Okay! Thank you very much!

  • How could I manage to access the name of the publisher next to the name and author of the book?

1 answer

0

As Woss commented in his question, you are making an inheritance, when in fact, what you need here is a composition.

You can change the book builder to receive a publisher:

class Book
   # code omitted...
   def initialize(title, author, editora)
     # code omitted...

After that, you define the method incrementNameTitle in Book, as now you are to receive the publisher in the builder, you will have access to what you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.