views:

52

answers:

2

I fired up irb, and typed:

class Point end

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

Irb didn't complain that I was defining a class that already exists.

+4  A: 

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

class String
  def bar
    "bar"
  end
end

"foo".bar # => "bar"

This feature is called "Open Classes." It's a great feature, but you should be careful: use it carelessly and you will be patching like a monkey.

Yaser Sulaiman
+7  A: 

Actually you didn't redefine the Point class, you reopened it. A little code snippet to illustrate the difference:

class Point
  def foo
  end
end

class Point
  def bar
  end
end

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

It is also possible to really redefine classes, by using remove_const to remove the previous binding of the class name first:

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