«

»

Jul
10

Class : to_s or not to_s ? That is the name !

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

  1. sheril says:

    x = 1000000
    puts “#{x} “+x.class.to_s

    here i dnt understand the use of x.class.to_s?
    pls answer

  2. Hallelujah says:

    I do not understand your question. Can you be more precise?

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">