Can you redefine a class in ruby? or is it just in irb

I ran irb and typed:

class point end

and then I typed it again, but added some other things.

Irb did not complain that I am defining an existing class.

+6
ruby ruby-on-rails
source share
2 answers

In Ruby, you can always add methods to an existing class, even if its main:

class String def bar "bar" end end "foo".bar # => "bar" 

This feature is called Open Classes. This is a great feature, but you have to be careful: use it carelessly and you will be patched like a monkey .

+6
source share

In fact, you did not redefine the Point class, you opened it again. A small piece of code illustrating the difference:

 class Point def foo end end class Point def bar end end 

Point now has two methods: foo and bar . Therefore, the second definition of Point did not replace the previous definition, it was added to it. This is possible in ruby ​​scripts, as well as in irb (this is also possible with classes from the standard library, and not just with your own).

You can also really override classes using remove_const to remove the previous class name binding first:

 class Point def foo end end Object.send(:remove_const, :Point) class Point def bar end end Point.instance_methods(false) #=> ["bar"] 
+17
source share

All Articles