NameError
RubyERRORNotableName
Undefined name or constant
Quick Answer
Ensure constants are defined and required files are loaded before referencing them.
What this means
Raised when a variable, method, or constant name cannot be resolved. It is the parent of NoMethodError. Typically appears when referencing an undefined constant or an undefined local variable.
Why it happens
- 1Referencing an undefined constant or class
- 2Typo in a constant or variable name
- 3Missing require for a gem or file that defines the constant
Fix
Add the missing require
Add the missing require
require 'json'
data = JSON.parse('{"key":"value"}')Why this works
require loads the file that defines the constant, making it available in the current scope.
Code examples
Undefined constantruby
puts UndefinedClass.new # NameError: uninitialized constant UndefinedClass
Typo in constantruby
# Intended: ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFoud # typo # NameError: uninitialized constant ActiveRecord::RecordNotFoud
Safe constant lookupruby
if Object.const_defined?(:MyClass) MyClass.new else puts 'MyClass is not loaded' end
Same error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev