I am new to Ruby . I have a question with respect to using Inheritence in Ruby .
I have a class called as Doggy inside a file named Doggy.rb
class Doggy
def bark
puts "Vicky is barking"
end
end
I have written another class named Puppy in another file named puppy.rb
class Puppy < Doggy
end
puts Doggy.new.bark
I am getting this Error:
Puppy.rb:1:in `<main>': uninitialized constant Doggy (NameError)
Is it mandatory to have these classes (Doggy and Puppy ) inside a single file only?
Edited
As per the suggestions , i have tried using require and require_relative as shown , but still i am getting below Error
Puppy.rb:1:in `<main>': uninitialized constant Doggy (NameError)
class Puppy < Doggy
end
require_relative 'Doggy.rb'
puts Doggy.new.bark
Ruby does not support multiple inheritance. It only supports single-inheritance (i.e. class can have only one parent), but you can use composition to build more complex classes using Modules.
In Ruby, single class inheritance is supported, which means that one class can inherit from the other class, but it can't inherit from two super classes. In order to achieve multiple inheritance, Ruby provides something called mixins that one can make use of.
Ruby uses the super keyword to call the superclass implementation of the current method. Within the body of a method, calls to super acts just like a call to that original method. The search for a method body starts in the superclass of the object that was found to contain the original method.
The Ruby class Class inherits from Module and adds things like instantiation, properties, etc – all things you would normally think a class would have. Because Module is literally an ancestor of Class , this means Modules can be treated like classes in some ways.
Changes to be done in puppy.rb file
Assuming both files are in the same directory, you're expected to require the file in the following way:
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
You should require file with Doggy
class in it from file where Puppy
is. Put
require './doggy'
or, if you are on ruby-1.9:
require_relative 'doggy'
in puppy.rb
(assuming file names are doggy.rb and puppy.rb).
Also, in addition to what everyone else has said, puts Dog.new.bark
will always fail, because your class is not called Dog, it's Doggy. Beware.
Not necessary, you have to require the file where Doggy
is declared. You can use require or require_relative.
Then, anyway make sure you use the name you declared: Doggy
and not Dog
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With