mhaseeb
mhaseeb

Reputation: 1779

Inheritance in Ruby

Everything is an object in Ruby. So if we have a class Hello it is an instance of a parent class Object.

If I do the following in Ruby:

Hello = Class.new
World = Class.new(Hello)

Does that translate into the following?

class Hello
class World < Hello

Since multiple inheritance can't be done in Ruby, the new method should take only one parameter?

Upvotes: 1

Views: 99

Answers (2)

BroiSatse
BroiSatse

Reputation: 44725

Yes and no. Yes, because as you wrote, it would end up with the same result (assuming you would add missing ends). No, as there is small difference in general case. To define anything within Class.new, you need to pass a ruby block, which is carrying, and has a full access to, the context it has been created in. So:

value = :hello

Hello = Class.new do
  define_method value do
    value
  end
end

Hello.new.hello #=> :hello
value = :world
Hello.new.hello #=> :world

Note that the name of the method did not change. However, the value it returns did. This is not ideal and is the reason why class Hello is preferred in most of the cases to avoid doing it by accident (same as def keyword being preferred over define_method).

This will not work with class keyword, as it does not create ruby block:

class Hello2
  define_method value do
    value
  end
end

#=> undefined local variable or method `value`

One more interesting fact about classes and constants is a behaviour of name method:

my_variable = Class.new
my_variable.name #=> nil

Hello = my_variable
my_variable.name #=> "Hello"

World = my_variable
my_variable.name #=> "Hello"

Upvotes: 2

sawa
sawa

Reputation: 168259

Yes. Positive to both (except that your latter code is invalid).

Note that your "Hello it is an instance of a parent class Class." is wrong. Hello is an instance of Class, but its parent is not Class, it's Object.

Upvotes: 4

Related Questions