Local variables store temporary information inside a small part of your program. Naming them clearly helps you and others understand what the program does.
0
0
Local variables and naming conventions in Ruby
Introduction
When you need to keep track of a value inside a method or block.
When you want to store a temporary result to use later in the same part of the program.
When you want to avoid changing data outside the current method or block.
When you want your code to be easy to read by giving meaningful names to values.
When you want to prevent mistakes by using proper naming rules.
Syntax
Ruby
variable_name = value
Local variable names start with a lowercase letter or underscore.
Use only letters, numbers, and underscores; no spaces or special characters.
Examples
A simple local variable named
count holding the number 10.Ruby
count = 10Local variable names can start with an underscore.
Ruby
_temp = "hello"Use underscores to separate words for better readability.
Ruby
user_name = "Alice"Sample Program
This program uses local variables name and greeting_message inside the greet method to store and print a greeting.
Ruby
def greet name = "Bob" greeting_message = "Hello, #{name}!" puts greeting_message end greet
OutputSuccess
Important Notes
Local variables only exist inside the method or block where they are created.
Choose clear and descriptive names to make your code easier to understand.
Do not start local variable names with capital letters; those are for constants or classes.
Summary
Local variables hold temporary data inside methods or blocks.
Names start with lowercase letters or underscores and use only letters, numbers, and underscores.
Good naming helps keep code clear and easy to read.