Blankman
Blankman

Reputation: 266920

are you allowed to redefine a class in ruby? or is this just in irb

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.

Upvotes: 9

Views: 5473

Answers (2)

Yaser Sulaiman
Yaser Sulaiman

Reputation: 3351

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.

Upvotes: 8

sepp2k
sepp2k

Reputation: 370102

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"]

Upvotes: 24

Related Questions