Warnings and deprecations
suggest changeA warning is a message Ruby prints to $stderr without stopping the program. Warnings point at code that works today but is probably wrong (a method defined twice), uses a feature that may change (Ractors), is slow (redefining Integer#+), or uses something that will be removed in a future version.
Ruby's warning system has grown a lot since 2.7:
- Ruby 2.7 added warning categories and
Warning[:category], with:deprecatedand:experimental. Since 2.7.2, deprecation warnings are off by default. - Ruby 3.0 added the
category:keyword toKernel#warn, andWarning.warnreceives the category. - Ruby 3.3 added the
:performancecategory. - Ruby 3.4 added the
:strict_unused_blockcategory andWarning.categories.
All output below comes from Ruby 4.0.7.
Verbosity: $VERBOSE
The global $VERBOSE controls how much Ruby warns. It has three values, and you can set it from the command line:
| Flag | $VERBOSE |
What is printed |
|---|---|---|
-W0 |
nil |
no warnings at all, warn prints nothing |
-W1 (the default) |
false |
important warnings and warn output |
-W2, -W, -w, -v |
true |
also "verbose" warnings |
-v also prints the Ruby version. Let's see the difference:
p $VERBOSE, Warning[:deprecated], Warning[:experimental]
warn "warn() output"
def a = 1
def a = 2
$ ruby v.rb
false
false
true
warn() output
$ ruby -W0 v.rb
nil
false
false
$ ruby -w v.rb
true
true
true
warn() output
v.rb:4: warning: method redefined; discarding old a
v.rb:3: warning: previous definition of a was here
Notice:
- "method redefined" is a verbose-only warning, so you only see it with
-w. -walso turns on the:deprecatedcategory.-W0turns off everything, includingwarncalls in your own code and the:experimentalcategory.
Running your test suite with -w is a cheap way to find bugs: duplicate method definitions, unused variables, if x = 1 instead of ==, and similar mistakes.
$VERBOSE can be changed at runtime. Code can use it to print extra details only in verbose mode:
def report_exhausted(waited, pool)
warn "connection pool exhausted, waited #{waited}ms"
warn "pool state: #{pool.inspect}" if $VERBOSE
end
report_exhausted(250, {size: 5, busy: 5})
$ ruby pool.rb
connection pool exhausted, waited 250ms
$ ruby -w pool.rb
connection pool exhausted, waited 250ms
pool state: {size: 5, busy: 5}
Warning categories
On top of the verbosity level, some warnings belong to a category that is turned on or off separately. Warning.categories lists them:
p Warning.categories
Warning.categories.each { |c| puts "#{c}: #{Warning[c]}" }
$ ruby cats.rb
[:deprecated, :experimental, :performance, :strict_unused_block]
deprecated: false
experimental: true
performance: false
strict_unused_block: false
| Category | Default | Example |
|---|---|---|
:deprecated |
off (on with -w) |
ObjectSpace._id2ref is deprecated |
:experimental |
on | Ractor API is experimental |
:performance |
off (not turned on by -w) |
Redefining 'Integer#+' disables interpreter and JIT optimizations |
:strict_unused_block |
off (not turned on by -w) |
the block passed to 'Report#render' ... may be ignored |
Warnings without a category (like "method redefined") are controlled only by $VERBOSE.
Here's a program that triggers warnings from each category:
r = Ractor.new { 1 + 2 }
p r.value
buf = IO::Buffer.new(4)
p buf.size
$, = "-"
p ObjectSpace._id2ref(nil.object_id)
s = "abc"
s << "d"
class Integer
def +(o) = o
end
def no_block = 1
no_block { 2 }
With the defaults, you only see the experimental warnings:
$ ruby kinds.rb
kinds.rb:1: warning: Ractor API is experimental and may change in future versions of Ruby.
3
kinds.rb:3: warning: IO::Buffer is experimental and both the Ruby and C interface may change in the future!
4
nil
-w adds the deprecation warnings and the verbose ones:
$ ruby -w kinds.rb
kinds.rb:1: warning: Ractor API is experimental and may change in future versions of Ruby.
3
kinds.rb:3: warning: IO::Buffer is experimental and both the Ruby and C interface may change in the future!
4
kinds.rb:5: warning: non-nil '$,' is deprecated
kinds.rb:6: warning: ObjectSpace._id2ref is deprecated
nil
kinds.rb:8: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
kinds.rb:10: warning: method redefined; discarding old +
kinds.rb:13: warning: the block passed to 'Object#no_block' defined at kinds.rb:12 may be ignored
The warning on line 8 is about chilled strings, explained in Frozen string literals and chilled strings.
The :performance category needs to be turned on explicitly:
$ ruby -W:performance -W:strict_unused_block kinds.rb
kinds.rb:1: warning: Ractor API is experimental and may change in future versions of Ruby.
3
kinds.rb:3: warning: IO::Buffer is experimental and both the Ruby and C interface may change in the future!
4
nil
kinds.rb:10: warning: Redefining 'Integer#+' disables interpreter and JIT optimizations
kinds.rb:13: warning: the block passed to 'Object#no_block' defined at kinds.rb:12 may be ignored
Ruby optimizes basic operations like Integer#+ and Array#[], and redefining them turns those optimizations off for the whole process. Another :performance warning is about objects whose instance variables are set in many different orders, which makes instance variable access slower:
Warning[:performance] = true
class Point
def initialize(n)
instance_variable_set("@v#{n}", n)
end
end
10.times { |i| Point.new(i) }
$ ruby perf.rb
perf.rb:4: warning: The class Point reached 8 shape variations, instance variables accesses will be slower and memory usage increased.
It is recommended to define instance variables in a consistent order, for instance by eagerly defining them all in the #initialize method.
See Performance for more about making Ruby code fast.
Unused blocks
Passing a block to a method that never uses it is a common mistake, for example when the method was refactored and no longer calls yield. With -w, Ruby warns about it, but only if no method with that name anywhere in the program uses a block. :strict_unused_block removes that exception:
class Report
def render = "report"
end
class Page
def render = yield
end
def plain = 1
Report.new.render { "ignored" }
plain { "ignored" }
$ ruby -w ub.rb
ub.rb:10: warning: the block passed to 'Object#plain' defined at ub.rb:7 may be ignored
$ ruby -W:strict_unused_block ub.rb
ub.rb:9: warning: the block passed to 'Report#render' defined at ub.rb:2 may be ignored
ub.rb:10: warning: the block passed to 'Object#plain' defined at ub.rb:7 may be ignored
Report#render isn't flagged by plain -w because Page#render takes a block, and Ruby can't tell which render will be called. The strict mode reports more false positives in code that passes blocks around generically, so it's off even with -w.
Turning categories on and off
From the command line, use -W:name to turn a category on and -W:no-name to turn it off. The flags can be combined with -w:
$ ruby -w -W:no-deprecated v.rb
true
false
true
warn() output
v.rb:4: warning: method redefined; discarding old a
v.rb:3: warning: previous definition of a was here
To set flags without changing the command, for example in CI or for a Rails server, put them in the RUBYOPT environment variable:
$ RUBYOPT="-W:deprecated -W:no-experimental" ruby kinds.rb
3
4
kinds.rb:5: warning: non-nil '$,' is deprecated
kinds.rb:6: warning: ObjectSpace._id2ref is deprecated
nil
kinds.rb:8: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
In PowerShell, use $env:RUBYOPT = "-W:deprecated".
From Ruby code, assign to Warning[]. It has to run before the code that warns, so put it at the top of the main script or in the test helper:
Warning[:experimental] = false
Warning[:deprecated] = true
Turning off only :experimental is common when you knowingly use an experimental feature. The WebSockets and TLS and HTTPS examples do that because the gems they use rely on IO::Buffer. It's better than $VERBOSE = nil, which also hides everything else.
Emitting your own warnings
Kernel#warn prints its arguments to $stderr, each on its own line. Two keyword arguments make it useful for library authors:
uplevel: nadds thefile:line: warning:prefix of the callernframes up.uplevel: 0is the line with thewarncall,uplevel: 1is the code that called the current method.category: :deprecated(or any other category) tags the warning. If that category is turned off, the warning is dropped.
module Legacy
def self.fetch(url)
warn "Legacy.fetch is deprecated, use HTTP.get", uplevel: 1, category: :deprecated
"body of #{url}"
end
end
Legacy.fetch("a")
Warning[:deprecated] = true
Legacy.fetch("b")
begin
warn "x", category: :oops
rescue ArgumentError => e
p e
end
warn "a", "b", uplevel: 0
$ ruby cat.rb
cat.rb:9: warning: Legacy.fetch is deprecated, use HTTP.get
#<ArgumentError: unknown category: oops>
cat.rb:15: warning: a
b
The first call on line 7 printed nothing, because deprecation warnings were still off. The category must be one of Warning.categories; you can't invent your own. Stack traces has more about uplevel: and caller locations.
Tagging deprecations with category: :deprecated is the polite thing to do: users who haven't asked for deprecation warnings don't get spammed, and users who run their tests with -W:deprecated see every call site.
A deprecate helper
When renaming many methods, a helper keeps the old names working and warns once per call site:
module Deprecation
def deprecate(old_name, new_name, version:)
owner = name
seen = {}
define_method(old_name) do |*args, **kw, &blk|
site = caller_locations(1, 1).first
key = [site.path, site.lineno]
if Warning[:deprecated] && !seen[key]
seen[key] = true
warn "#{owner}##{old_name} is deprecated and will be removed in #{version}; " \
"use ##{new_name}", uplevel: 1, category: :deprecated
end
public_send(new_name, *args, **kw, &blk)
end
end
end
class Mailer
extend Deprecation
def deliver(to, subject:) = "sent #{subject.inspect} to #{to}"
deprecate :send_mail, :deliver, version: "3.0"
end
m = Mailer.new
p m.send_mail("a@example.com", subject: "hi") # silent: category is off
Warning[:deprecated] = true
3.times { m.send_mail("b@example.com", subject: "loop") }
p m.send_mail("c@example.com", subject: "bye")
$ ruby deprecate.rb
"sent \"hi\" to a@example.com"
deprecate.rb:29: warning: Mailer#send_mail is deprecated and will be removed in 3.0; use #deliver
deprecate.rb:30: warning: Mailer#send_mail is deprecated and will be removed in 3.0; use #deliver
"sent \"bye\" to c@example.com"
The loop on line 29 warns once instead of three times. The wrapper forwards keyword arguments with **kw, which matters since Ruby 3.0; see Keyword arguments in Ruby 3.
RubyGems ships a similar helper, Gem::Deprecate (extend Gem::Deprecate and deprecate :get_all, :fetch_all, 2027, 6). It prints a NOTE: message on every call without a category, so Warning[:deprecated] and -W:no-deprecated have no effect on it. Only -W0 or Gem::Deprecate.skip_during { ... } silence it. Prefer warn ... category: :deprecated.
Customizing Warning.warn
Every warning, whether it comes from the interpreter, a C extension or Kernel#warn, ends up in Warning.warn(message, category: nil). The default implementation writes the message to $stderr. Override it and you control what happens to all warnings in the process:
module Warning
def self.warn(message, category: nil)
print "[#{category.inspect}] #{message.inspect}\n"
end
end
Warning[:deprecated] = true
warn "hello"
warn "old api", category: :deprecated
$, = "-"
Ractor.new {}.join
def m = 1
def m = 2
$VERBOSE = true
def m = 3
$ ruby ov.rb
[nil] "hello\n"
[:deprecated] "old api\n"
[:deprecated] "ov.rb:9: warning: non-nil '$,' is deprecated\n"
[:experimental] "ov.rb:10: warning: Ractor API is experimental and may change in future versions of Ruby.\n"
[nil] "ov.rb:14: warning: method redefined; discarding old m\nov.rb:12: warning: previous definition of m was here\n"
A few things to know:
- The message already contains the
file:line: warning:prefix (when there is one) and ends with a newline. A warning can span several lines, like the method redefinition above. - Filtering happens before
Warning.warnis called. The redefinition on line 12 didn't reach it because$VERBOSEwasfalsethen, and a disabled category is never passed in. - If your override doesn't declare
category:, Ruby calls it with just the message.
Defining self.warn directly replaces the original, so there is no super to fall back on. To keep the default behavior for some warnings, put your method in a module and extend Warning with it:
module QuietExperimental
def warn(message, category: nil, **kw)
return if category == :experimental
super
end
end
Warning.extend(QuietExperimental)
Ractor.new {}.join
warn "still shown"
$ ruby ov3.rb
still shown
Sending warnings to a logger
In a long-running service, $stderr may not be collected anywhere. Route warnings to the application's logger instead (see Logging):
require "logger"
LOG = Logger.new($stdout, progname: "ruby")
LOG.formatter = proc { |sev, _time, prog, msg| "#{sev} #{prog}: #{msg}\n" }
module Warning
def self.warn(message, category: nil)
text = message.chomp
text = "[#{category}] #{text}" if category
LOG.warn(text)
end
end
Warning[:deprecated] = true
warn "cache size is low"
warn "Config#load is deprecated", category: :deprecated
$, = ","
$, = nil
$ ruby log.rb
WARN ruby: cache size is low
WARN ruby: [deprecated] Config#load is deprecated
WARN ruby: [deprecated] log.rb:17: warning: non-nil '$,' is deprecated
Turning on :deprecated in production and logging it is a good way to collect the list of things to fix before a Ruby or gem upgrade.
Failing tests on warnings
Warnings are easy to ignore when they scroll by in test output. A stricter approach is to make any warning that comes from your own code fail the test that caused it. With Minitest:
# test/test_helper.rb
require "minitest/autorun"
Warning[:deprecated] = true
Warning[:performance] = true
module FailOnWarnings
ROOT = File.expand_path("..", __dir__)
CAPTURED = []
def warn(message, category: nil, **)
file = message[/\A(.+?):\d+: warning:/, 1]
return super unless file && File.expand_path(file).start_with?(ROOT)
CAPTURED << message
end
end
Warning.extend(FailOnWarnings)
class Minitest::Test
def after_teardown
super
found = FailOnWarnings::CAPTURED.dup
FailOnWarnings::CAPTURED.clear
flunk "Ruby warnings:\n#{found.join}" unless found.empty?
end
end
Warnings whose location is outside the project directory, for example from installed gems, and plain warn calls without a location are printed normally. Here is the code under test and the tests:
# lib/pricing.rb
module Pricing
def self.total(items)
items.sum { it[:price] }
end
def self.sum(items)
warn "Pricing.sum is deprecated, use Pricing.total",
uplevel: 1, category: :deprecated
total(items)
end
end
# test/pricing_test.rb
require_relative "test_helper"
require_relative "../lib/pricing"
class PricingTest < Minitest::Test
ITEMS = [{price: 3}, {price: 4}]
def test_total
assert_equal 7, Pricing.total(ITEMS)
end
def test_sum
assert_equal 7, Pricing.sum(ITEMS)
end
end
$ ruby test/pricing_test.rb --seed 1
Run options: --seed 1
# Running:
F.
Finished in 0.001148s, 1741.7051 runs/s, 2612.5577 assertions/s.
1) Failure:
PricingTest#test_sum [test/test_helper.rb:24]:
Ruby warnings:
test/pricing_test.rb:13: warning: Pricing.sum is deprecated, use Pricing.total
2 runs, 3 assertions, 1 failures, 0 errors, 0 skips
The test still calls the deprecated method, so the warning points at it and the failure tells you which test to update. Warnings emitted at load time, before any test runs, are attributed to the first test that finishes. Testing in CI shows a simpler version that raises on every warning when the CI variable is set.
The warning gem
The warning gem wraps Warning.warn with a small API for ignoring, deduplicating and processing warnings by message and file path:
require "warning"
Warning[:deprecated] = true
Warning.ignore(/./, File.expand_path("vendor", __dir__))
Warning.process(File.expand_path("lib", __dir__)) { :raise }
Warning.dedup
require_relative "vendor/noisy"
require_relative "lib/app"
Noisy.go
2.times { warn "top-level warning" }
begin
app_run
rescue => e
p e.class
puts e.message.delete_prefix("#{__dir__}/")
end
vendor/noisy.rb and lib/app.rb both call warn "...", uplevel: 0, category: :deprecated.
$ ruby wg.rb
top-level warning
RuntimeError
lib/app.rb:2: warning: app: old option
Warning.ignore(regexp, path)drops warnings whose message starts withpathand matches the regexp. It also accepts symbols for common warnings, like:method_redefined, instead of a regexp.Warning.process(path) { |message| ... }runs the block for matching warnings. Returning:raiseturns the warning into an exception,:defaultprints it, and:backtraceprints it with a backtrace.Warning.dedupprints each distinct message only once, which is why "top-level warning" appears once.
The path is matched as a string prefix of the message, so pass absolute paths for files loaded with require.
Silencing warnings temporarily
Sometimes you have to call code that you know warns, for example loading an old library. Set $VERBOSE to nil around the call:
def silence_warnings
old, $VERBOSE = $VERBOSE, nil
yield
ensure
$VERBOSE = old
end
silence_warnings do
warn "you won't see this"
Ractor.new {}.join
end
warn "but you will see this"
p $VERBOSE
$ ruby silence.rb
but you will see this
false
$VERBOSE is global, not per thread, so while the block runs, warnings from other threads are silenced too. Keep these blocks short and prefer turning off a specific category, or filtering by path in Warning.warn, when you can.
Preparing for an upgrade
Deprecation warnings are how Ruby and gems announce what will break in the next major version. A practical routine:
- Run the test suite with deprecations on:
RUBYOPT="-W:deprecated" bundle exec rake test, or-wfor everything. - Fix warnings in your own code first. Filter warnings from gems by path and check whether a newer gem version fixes them.
- Once the output is clean, keep it clean by failing tests on new warnings from your code, as shown above.
Past examples of this: Ruby 2.7 warned about the keyword argument changes that became errors in 3.0 (see Keyword arguments in Ruby 3), and Ruby 3.4 started warning about mutating string literals, which will be frozen in a future version (see Frozen string literals and chilled strings). In both cases the warnings were off by default, so only projects that turned on :deprecated saw them coming.