is identation madatory in ruby
Yes, indentation is mandatory in Ruby for indicating the structure and scope of code blocks. Ruby uses indentation to define the beginning and end of blocks of code. The standard convention is to use two spaces for each level of indentation. Here is an example:
def example_method
if some_condition
puts "Condition is true"
else
puts "Condition is false"
end
3.times do |i|
puts "Iteration #{i + 1}"
end
end
example_method
In this example:
- The method example_method
is defined using the def
keyword.
- Inside the method, there is an if
statement that checks a condition. The code inside the if
block is indented to indicate it is part of the if
statement.
- Similarly, the else
block is indented.
- Inside the else
block, there is a loop (3.times
) with a block of code. The code inside the block is indented to indicate it belongs to the loop.
Indentation is crucial for readability and understanding the structure of the code. It helps in visually identifying the hierarchy of code blocks and improves code maintainability.