Causes of Ruby NameError: Uninitialized Constant Error

Understand NameError Causes and How to Troubleshoot Them

Picture of a caucasian businessman working in an office
© Jetta Productions / Blend Images / 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 the regular NameError exception class. It has several 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 ruby

module MyModule
 class MyClass; end

c =

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, Argument Error and others. This class includes most of the normal exceptions that you encounter in typical Ruby programs.

For additional information on Ruby, see:

Is the 'Require' Method Overlooked in Ruby?

Using Attributes

Using Comments in Ruby

Using Environment Variables in Ruby

Command-Line Arguments in Ruby