NameError

Has approximate knowledge of many things.

Ruby's NameError class

Raised when a given name is invalid or undefined.

puts foo

raises the exception:

NameError: undefined local variable or method `foo' for main:Object

Since constant names must start with a capital:

Integer.const_set :answer, 42

raises the exception:

NameError: wrong constant name answer

Superclass

StandardError

Methods

  • name
  • receiver
  • local_variables

Enemies

Honeybadger

Children

» What's in a Name?

NameError is raised when you reference a constant or a variable which isn't defined in the current context. A ruby constant can be a Module, Class, or a CONSTANT_VARIABLE, and must always start with an upper case letter.

You may encounter NameError when:

  • There is a typo in your variable name, class name, module name or constant name.
  • The file with the class definition isn't loaded in the current context.
  • The rubygem which defines these constants is not loaded.
  • Full name of the constant not being used, e.g., when you use PI instead of Math::PI

Another instance of this occurs when you try to define a constant starting with a lower case letter.

» Examples

» 1. Missing Require:

irb> SecureRandom.uuid
NameError: uninitialized constant SecureRandom
Did you mean?  SecurityError

Fixing it with a require.

require 'securerandom'
SecureRandom.uuid
# => "22fb1159-5241-4a5c-a3ff-12579f13fb37"

» 2. Typos:

Aray.new
# => NameError: uninitialized constant Aray
# => Did you mean?  Array

Fixing it with the correct spelling:

irb> Array.new
# => []

» 3. Incorrect Path:

module Config
  module Site
    NAME = "spongebob"
  end

  def self.print_name
    puts NAME
  end
end

Config.print_name
# => ...:19:in `print_name': uninitialized constant Config::NAME (NameError)
# => ...:23:in `<main>'

Fixing it with the correct path:

module Config
  module Site
    NAME = "spongebob"
  end

  def self.print_name
    puts Site::NAME
  end
end

Config.print_name
# => spongebob

» Easier Debugging Using did_you_mean

did_you_mean is a nifty gem which helps you when you run into NameError because of typos. The gem is included by default in Ruby 2.3 and later. If you use an older version of Ruby, include did_you_mean in your Gemfile to help you debug better:

Fle.readlines "/tmp/x"
# => NameError: uninitialized constant Fle
# => Did you mean?  File

did_you_mean also helps when you run into a NoMethodError.

» Conditionally Referencing Constants

Sometimes you may want to know if a constant is loaded and do things conditionally. For instance, if you want to execute a chunk of code if the constant Rails is defined, you can use the defined? function:

if defined?(Rails)
  # execute this code conditionally when we have a constant called `Rails`
  # ...
end