Many rubyist use the method Class#to_s instead of Class#name
My purpose (shared by some programmers) is that to_s is just a String representation of the Class not its name!!
Imagine you want to store an ordered list of inherited subclasses as a String so you can retrieve the inheritance order of each subclass.
class Parent @@subclasses = [] def self.inherited(subclass) @@subclasses << "#{subclass}" end def self.inheritance_order @@subclasses.index("#{self}") end end class Child1 < Parent end class Child2 < Parent end # etc ...
And now you want to know, the inheritance order of Child2
Child2.inheritance_order #=> 1
As long as you don’t override Child2.to_s method, this works.
But if you decide to override it ….
def Child2.to_s "The second child of Parent" end Child2.inheritance_order #=> nil
Do you understand what I mean ? My purpose is that Class#to_s is a String representation, so you can do what you want with this method (as long as it returns a String instance)
If you want to write something more reliable, just change Class#to_s by Class#name :
class Parent @@subclasses = [] def self.inherited(subclass) @@subclasses << subclass.name end def self.inheritance_order @@subclasses.index(self.name) end end
What is your opinion ?


2 comments
sheril says:
July 29, 2010 at 18:26 (UTC 2 )
x = 1000000
puts “#{x} “+x.class.to_s
here i dnt understand the use of x.class.to_s?
pls answer
Hallelujah says:
August 3, 2010 at 00:44 (UTC 2 )
I do not understand your question. Can you be more precise?