Causes of Ruby NameError: Uninitialized Constant Error

Man with glasses using a laptop

Cultura RM Exclusive / Stefano Gilera / Getty Images

The open-source programming language Ruby is known for its clear syntax and ease of use. That doesn't mean you won't occasionally run into an error message. One of the most vexing is the NameError Uninitialized Constant exception because it has more than one cause. The syntax of the exception follows this format:

NameError: uninitialized constant Something


NameError: uninitialized constant Object::Something

(where various class names are in place of Something)

Ruby NameError Uninitialized Constant Causes

The Uninitialized Constant error is a variation of a regular NameError exception class. It has several possible causes. 

  • You'll see this error when the code refers to a class or module that it can't find, often because the code doesn't include require, which instructs the Ruby file to load the class.
  • In Ruby, variables/methods begin with lowercase letters, while classes begin with uppercase letters. If the code doesn't reflect this distinction, you'll receive the Uninitialized Constant exception.
  • Still another possible cause for the NameError error is that you've made a simple typo in the code. 
  • Ruby is case sensitive, so "TestCode" and "Testcode" are completely different. 
  • The code contains mention of rubygems, which is deprecated in all but old versions of Ruby.

How to Fix the Error

To troubleshoot your code, examine it for the possible causes listed above one at a time. If you find a problem, address it. For example, go through the code looking for a discrepancy in uppercase and lowercase usage on variables and classes. If you find one and correct it, your problem is probably solved. If it isn't, continue through the other possible causes, fixing as you go.

If the class you refer to in the code is in another module, refer to it with its full name like this:

#!/usr/bin/env rubymodule MyModule class MyClass; endendc =

About Ruby Exceptions

Exceptions are how Ruby draws your attention to problems in the code. When an error in the code is encountered, an exception is "raised" or "thrown" and the program shuts down by default.

Ruby publishes an exception hierarchy with predefined classes. NameErrors are in the StandardError class, along with RuntimeError, ThreadError, RangeError, ArgumentError and others. This class includes most of the normal exceptions that you encounter in typical Ruby programs.

mla apa chicago
Your Citation
Morin, Michael. "Causes of Ruby NameError: Uninitialized Constant Error." ThoughtCo, Aug. 26, 2020, Morin, Michael. (2020, August 26). Causes of Ruby NameError: Uninitialized Constant Error. Retrieved from Morin, Michael. "Causes of Ruby NameError: Uninitialized Constant Error." ThoughtCo. (accessed April 2, 2023).