Nikolas
Nikolas

Reputation: 188

Changing self class from inside a method?

Let's start off with the assumption I want a method that allows an object to transform itself into another object. Where B is a A object

(In B model) -->

def change_type
  self = self.becomes (A)
end

But anyway I can't can't change "self". How can I fix it? The cast must be in model.

Upvotes: 1

Views: 817

Answers (3)

Aetherus
Aetherus

Reputation: 8888

If class B inherits class A, then an instance of B is born an instance of A. No need to change.

class A; end

class B < A; end

b = B.new

b.is_a?(A)  #=> true

Upvotes: 0

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369428

You cannot change the class of an object once created, nor can you change an object into another object.

You are thinking of Smalltalk's become: method, which can make one object become another object (and thus as a special case also change an object's class). Ruby doesn't have that.

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230296

There's no way. You can't overwrite self. Or any object*, as a matter of fact.


* You can reassign reference/variable, but not the object itself.

Upvotes: 1

Related Questions