Ruby for Instance / Defer

# Define a method that uses the defer method
def example
  # Define a variable that will be used by the deferred block
  some_variable = "hello"

  # Defer the execution of a block of code
  defer { puts some_variable }

  # Modify the variable
  some_variable = "world"

  # Raise an error
  raise "An error occurred"
end

# Call the method
example

# The error will be raised, but the deferred block will still be executed
# => "world"

Try on playground

Next: JSON and XML

made with by dfxe / source / license