Errors in Ruby
In Ruby, it’s idiomatic to communicate errors via exceptions, which is different from the explicit error return values used in some other languages. Ruby’s approach makes it easy to handle errors using language constructs like begin
, rescue
, and ensure
.
When you run this Ruby script, you’ll get output similar to this:
In Ruby, we use exceptions for error handling. The raise
keyword is used to throw an exception, and rescue
is used to catch and handle exceptions. This is similar to try
/catch
in many other languages.
Ruby doesn’t have a built-in way to wrap errors like Go’s fmt.Errorf
with %w
, but you can achieve similar functionality by setting the cause
of an exception when you raise it, or by using custom exception classes that contain additional context.
The StandardError
class is the default superclass for all standard errors. You can create custom error classes by inheriting from StandardError
or any of its subclasses.
Ruby’s case
statement is used here as an equivalent to Go’s if
/else if
chain in the makeTea
function.
Remember that in Ruby, the last evaluated expression in a method is implicitly returned, so we don’t need explicit return
statements in many cases.
This example demonstrates how Ruby’s exception handling mechanism can be used to achieve similar error handling patterns as in Go, while following Ruby’s idiomatic practices.