Users can come across many types of warnings and errors while programming. Errors can halt the execution of the program while warnings notify users about upcoming errors. However, sometimes users may require warnings to be added into their codes to remind them to incorporate some change. In the Ruby programming language, there is a Kernel.warn
that can be redefined by the user to do whatever they want (including exiting the program). However, Kernel.warn
is mainly used to notify users of warnings within a code.
Warnings can be disabled with the -W0 flag, in such a case, the warn
method does not change anything. Others, a Warning converts each of the messages into strings, adds a newline if needed, and then calls the Warning.warn
, which produces the string:
warn("warning a", "warning b")
warning a
warning b
The parameters of a warning method are two strings separated by a newline. However, there is another parameter known as the uplevel
. If the uplevel keyword argument is given, the compiler invokes a native method (rb_warn
) from source/server.c
that completely bypasses the redefinition of Kernel.warn
and outputs a warning as an error. The code below gives an error and the desired output on line 5 when I try to call the foo
method.
Look at the code below for a basic example.
# in main.rbdef foowarn("invalid call to foo", uplevel: 1)endfoo# line 5 calls foo which returns a warning as defined by user.
Free Resources