Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 994
Blankman Avatar asked Sep 29 '10 14:09

Blankman


People also ask

Can we include class in Ruby?

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.

How do you define a class in Ruby?

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.

How do classes work in Ruby?

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.

Do you know what a class method is and how do you define one Ruby?

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.


2 Answers

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"]
like image 138
sepp2k Avatar answered Oct 29 '22 16:10

sepp2k


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.

like image 33
Yaser Sulaiman Avatar answered Oct 29 '22 16:10

Yaser Sulaiman