Ruby begin/end block
In the Ruby programming language, the begin
and end
keywords serve the purpose of creating block-like control structures. They allow us to group together multiple code statements within a block.
When utilizing lowercase begin/end
blocks, we can create generic reusable code blocks by grouping code statements together.
Furthermore, one common application of begin/end
is for exception handling.
By enclosing a block of code that might raise an exception within a begin/end
block, we can then handle that exception using the rescue
keyword.
begin
# code statements here
end
with rescue:
begin
# code that might raise exception
puts 10 / 0
rescue ZeroDivisionError => e
# code statements if exception is raised
puts "Error:#{e.message}"
end
end
#=> Error:divided by 0
Grouping of Code
result =
begin
product_count = 10
product_price = 200
product_count * product_price
end
puts result # Output will be 2000
end
The code block inside begin
and end
contains several statements.
The value of the last expression (product_count * product_price) is returned as the result of the block. This can be useful when you need to group multiple operations and return a single value.
Handling Exceptions
with rescue:
def safe_division(dividend, divisor)
begin
dividend / divisor
rescue ZeroDivisionError
puts "Cannot divide by zero"
end
end
puts safe_division(10, 0) #=> Cannot divide by zero
puts safe_division(10, 2) #=> 5
with ensure:
def safe_division(dividend, divisor)
begin
dividend / divisor
rescue ZeroDivisionError
print "Cannot divide by zero "
ensure
puts "#{dividend}/#{divisor}"
end
end
puts safe_division(10, 0) #=> Cannot divide by zero 10/0
puts safe_division(10, 2) #=> 10/2; 5