What the difference given they all exist 'once per class'.
When should I use one over another, i.e. for what purpose?
I use Ruby.

  • 1
    I am not a ruby programmer but my favorite search engine brings up the answer very easily - is there anything you do not understand in particular? The difference between attribute, constants and methods are VERY basic. (And singleton methods do not exist in a class but are given to a single object, see rubyist.net/~slagell/ruby/singletonmethods.html )
    – scarfridge
    Commented Jun 17, 2012 at 10:14

1 Answer 1


The differences are well-defined, and you can look them up easily. Here's a quick (language-agnostic) summary:

  • Class constants are constant, you cannot change them at run-time at all. They are made part of the class because they belong to it, conceptually speaking, and also often (but not always) to limit their scope and/or avoid naming clashes.
  • Class-level attributes (static fields) are just global variabls in disguise - they are scoped inside the class, but other than that, they are global. In contrast with class constants, they are read/write, so their value can change at run-time.
  • Singleton methods are, in fact, regular methods, but the instance they belong to (the singleton) has been enforced to be the only one of its type within a particular context (what that context is differs between languages, platforms, and implementations).

As to which one to choose: My advice is to avoid class-level attributes and singletons as much as possible. Both are globals in disguise, and although there might be appropriate uses for them, most real-world applications are in fact inappropriate, introduced for "convenience" at one point, and a source of major headaches later on. In most situations, a better alternative is to create a regular type to describe the state that you would otherwise put in a class attribute or singleton, and just pass it around. This way, you can control exactly who gets to modify the state (and who doesn't), and should you ever decide that you do need more than one instance, you can just create one. The hassle of carrying the state object around is minimal in comparison.

Class constants, by contrast, are fine - they are constants, so there is no risk of unexpected changes. They are just values that you can access from anywhere, and there is nothing wrong with that (as long as the code that uses them doesn't break if you change the value).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.