|
| 1 | +# Ensure |
| 2 | + |
| 3 | +In Ruby, the `ensure` keyword is used to define a block of code that will always execute, regardless of whether an exception was raised or not. It's commonly used for cleanup operations like closing files or network connections. |
| 4 | + |
| 5 | +```ruby |
| 6 | +# Basic ensure usage |
| 7 | +file = File.open("example.txt") |
| 8 | +begin |
| 9 | + content = file.read |
| 10 | +rescue StandardError => e |
| 11 | + puts "Error reading file: #{e.message}" |
| 12 | +ensure |
| 13 | + file.close # Always executes |
| 14 | +end |
| 15 | +``` |
| 16 | + |
| 17 | +The `ensure` clause can be used with or without `rescue` blocks, and it will execute even if there's a return statement in the main block. |
| 18 | + |
| 19 | +```ruby |
| 20 | +def process_data |
| 21 | + connection = Database.connect |
| 22 | + begin |
| 23 | + return connection.query("SELECT * FROM users") |
| 24 | + ensure |
| 25 | + connection.close # Executes even with the return statement |
| 26 | + end |
| 27 | +end |
| 28 | + |
| 29 | +# Without rescue clause |
| 30 | +def write_log(message) |
| 31 | + file = File.open("log.txt", "a") |
| 32 | + begin |
| 33 | + file.puts(message) |
| 34 | + ensure |
| 35 | + file.close |
| 36 | + end |
| 37 | +end |
| 38 | +``` |
| 39 | + |
| 40 | +## Multiple Rescue Clauses |
| 41 | + |
| 42 | +When using multiple `rescue` clauses, the `ensure` block always comes last and executes regardless of which `rescue` clause is triggered. |
| 43 | + |
| 44 | +```ruby |
| 45 | +def perform_operation |
| 46 | + begin |
| 47 | + # Main operation |
| 48 | + result = dangerous_operation |
| 49 | + rescue ArgumentError => e |
| 50 | + puts "Invalid arguments: #{e.message}" |
| 51 | + rescue StandardError => e |
| 52 | + puts "Other error: #{e.message}" |
| 53 | + ensure |
| 54 | + # Cleanup code always runs |
| 55 | + cleanup_resources |
| 56 | + end |
| 57 | +end |
| 58 | +``` |
| 59 | + |
| 60 | +## Implicit Begin Blocks |
| 61 | + |
| 62 | +In methods and class definitions, you can use `ensure` without an explicit `begin` block. |
| 63 | + |
| 64 | +```ruby |
| 65 | +def process_file(path) |
| 66 | + file = File.open(path) |
| 67 | + file.read # If this raises an error, ensure still executes |
| 68 | +ensure |
| 69 | + file&.close # Using safe navigation operator in case file is nil |
| 70 | +end |
| 71 | + |
| 72 | +class DataProcessor |
| 73 | + def initialize |
| 74 | + @connection = Database.connect |
| 75 | + rescue StandardError => e |
| 76 | + puts "Failed to connect: #{e.message}" |
| 77 | + ensure |
| 78 | + puts "Initialization complete" |
| 79 | + end |
| 80 | +end |
| 81 | +``` |
| 82 | + |
| 83 | +The `ensure` keyword is essential for writing robust Ruby code that properly manages resources and handles cleanup operations, regardless of whether exceptions occur. |
0 commit comments