开发者

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

开发者 https://www.devze.com 2023-01-17 21:50 出处:网络
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 cl开发者_如何学JAVAass that already exists.Actually y

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 cl开发者_如何学JAVAass that already exists.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消