Using Multiple File Inheritance in Ruby

I am new to Ruby. I have a question regarding the use of Inheritence in Ruby.

I have a class called Doggy inside a Doggy.rb file

class Doggy def bark puts "Vicky is barking" end end 

I wrote another class called Puppy in another file called puppy.rb

 class Puppy < Doggy end puts Doggy.new.bark 

I get this error:

 Puppy.rb:1:in `<main>': uninitialized constant Doggy (NameError) 

Is it mandatory to use these classes (Doggy and Puppy) in only one file?

Edited by

As suggested, I tried using require and require_relative as shown, but still I get below Error

 Puppy.rb:1:in `<main>': uninitialized constant Doggy (NameError) class Puppy < Doggy end require_relative 'Doggy.rb' puts Doggy.new.bark 
+4
source share
6 answers

Changes made to puppy.rb require a file as follows. Assuming both files are in the same directory.

doggy.rb

 class Doggy def bark puts "Vicky is barking" end end 

puppy.rb

 require File.expand_path('../doggy.rb', __FILE__) class Puppy < Doggy end puts Doggy.new.bark 
+4
source

You must require a file with the Doggy class in it from the file where Puppy . Placed

 require './doggy' 

or if you are on ruby-1.9:

 require_relative 'doggy' 

in puppy.rb (provided that the file names are doggy.rb and puppy.rb).

+4
source

Also, in addition to what everyone else said, puts Dog.new.bark will always fail because your class is not called Dog , it's Doggy. Caution.

+1
source

No need, you need to specify the file in which Doggy declared. You can use require or require_relative .

Then, at any rate, make sure that you use the name you provided: Doggy , not Dog .

+1
source

A file containing the Doggy definition is loaded after you inherit it from Doggy . Of course, this may not work. How can you inherit from Doggy on line 1 if you only upload a file containing the definition of Doggy on line 3?

+1
source

You must include Doggy.rb in the Puppy class.

0
source

Source: https://habr.com/ru/post/1433203/


All Articles