Kernel#autoload
autoload(const_name, filename) -> nil Returns:
nil · Updated March 13, 2026 · Kernel Methods loading constants lazy performance
The autoload method defers the loading of a Ruby file until a specific constant is actually used. This improves startup time by only loading code when it’s needed.
How It Works
When you call autoload, you specify a constant name and a file path. Ruby won’t load the file until something tries to reference that constant. Once loaded, the constant is available just as if you’d required the file.
Practical Examples
Basic Setup
# In some initialization file
autoload :User, 'models/user'
autoload :Product, 'models/product'
# When User is first referenced, models/user.rb is loaded
user = User.find(1) # File loaded here on first use
File Naming Conventions
# autoload expects file path, not class name
# This looks for 'models/user.rb'
autoload :User, 'models/user'
# For namespaced classes
autoload :AdminUser, 'models/admin/user'
Module Setup
module Services
autoload :Email, 'services/email'
autoload :Payment, 'services/payment'
autoload :Notification, 'services/notification'
end
# First use loads the file
Services::Email.send_welcome(user)
Comparison with require
# require loads immediately
require 'heavy_library' # Slow startup
# autoload loads on first use
autoload :HeavyLibrary, 'heavy_library'
# Fast startup, but first use is slower
Use Cases
Large Applications
# Rails-like autoloading
# Only load admin code when admin is used
autoload :AdminController, 'controllers/admin_controller'
# Only load reporting when needed
autoload :ReportGenerator, 'services/report_generator'
Plugin Systems
module MyApp
# Register plugins lazily
autoload :MarkdownPlugin, 'plugins/markdown'
autoload :SyntaxPlugin, 'plugins/syntax'
end
Important Notes
# autoload only works with constants (capitalized)
autoload :MyClass, 'my_class'
autoload :MY_CONSTANT, 'constants/my_constant'
# Won't work with lowercase
# autoload :variable, 'file' # Error!
# Can check if constant is defined
defined?(User) # => nil if not loaded, "constant" if loaded
With Namespaces
# Module handles the namespace
module Admin
autoload :User, 'admin/user'
end
# Access as
Admin::User
Modern Alternatives
In Ruby 3+, consider using Zeitwerk for automatic gem loading, but autoload remains useful for custom lazy loading strategies.