How to Declare Variables in Ruby: Simple Guide
In Ruby, you declare a variable by simply writing its name followed by an equal sign and the value, like
name = "Alice". Ruby variables do not need explicit type declarations and can hold any type of data.Syntax
To declare a variable in Ruby, write the variable name, then an equal sign =, followed by the value you want to store. Variable names usually start with a lowercase letter or underscore.
- Variable name: A name you choose to identify the variable.
- =: Assignment operator that stores the value.
- Value: The data you want to keep, like a number, text, or object.
ruby
variable_name = value # Examples: age = 25 name = "Bob" price = 19.99
Example
This example shows how to declare variables with different types of values and then print them.
ruby
name = "Alice" age = 30 is_student = true puts "Name: #{name}" puts "Age: #{age}" puts "Student? #{is_student}"
Output
Name: Alice
Age: 30
Student? true
Common Pitfalls
Some common mistakes when declaring variables in Ruby include:
- Using variable names that start with a capital letter, which Ruby treats as constants.
- Trying to use variables before assigning them a value, which causes errors.
- Using spaces around the
=sign incorrectly (spaces are allowed but avoid confusing syntax).
ruby
1. # Wrong: variable name starts with capital letter (treated as constant) Name = "Alice" 2. # Wrong: using variable before assignment puts age age = 25 # Correct way: age = 25 puts age
Output
NameError: uninitialized constant Name
# For the second snippet, the first puts will cause an error because age is not assigned yet.
Quick Reference
Remember these tips when declaring variables in Ruby:
- Variable names start with lowercase letters or underscores.
- No need to declare type; Ruby figures it out.
- Use
=to assign values. - Constants start with uppercase letters and should not change.
Key Takeaways
Declare variables by writing the name, then =, then the value.
Variable names start with lowercase letters or underscores, not capitals.
Ruby variables do not need explicit types; they can hold any data.
Avoid using variables before assigning them a value to prevent errors.
Constants start with uppercase letters and behave differently from variables.