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.
Ruby allows you to create a class tied to a particular object. In the following example, we create two String objects. We then associate an anonymous class with one of them, overriding one of the methods in the object's base class and adding a new method.
Defining a class in Ruby: Simply write class keyword followed by the name of the class. The first letter of the class name should be in capital letter.
In Ruby, a class is an object that defines a blueprint to create other objects. Classes define which methods are available on any instance of that class. Defining a method inside a class creates an instance method on that class. Any future instance of that class will have that method available.
Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With