Ruby Basic Syntax
Ruby has concise and elegant syntax, making it easy to learn and use. This chapter introduces Ruby's basic syntax rules, including code structure, comments, variable naming, and other fundamentals.
📝 Ruby Code Structure
Program Entry
Ruby programs execute from top to bottom and don't require a specific entry function:
# Simple Ruby program
puts "Hello, World!"
puts "This is my first Ruby program"
# Output:
# Hello, World!
# This is my first Ruby programStatement Separator
Ruby statements don't require a semicolon at the end; a newline is the statement separator:
# Correct写法
name = "Zhang San"
age = 25
puts name
puts age
# Can also use semicolons (not recommended)
name = "Li Si"; age = 30; puts name; puts ageCode Blocks
Ruby uses do...end keywords or curly braces {} to define code blocks:
# Using do...end
5.times do
puts "Hello"
end
# Using curly braces (single-line code block)
5.times { puts "Hello" }
# Code block with parameters
[1, 2, 3, 4, 5].each do |number|
puts "Number: #{number}"
end💬 Comments
Single-Line Comments
Use # symbol to add single-line comments:
# This is a single-line comment
puts "Hello, World!" # This is also a comment, following code
# Calculate sum of two numbers
sum = 5 + 3 # 5 plus 3 equals 8Multi-Line Comments
Use =begin and =end to enclose multi-line comments:
=begin
This is a multi-line comment
Can contain multiple lines of content
Used to explain code functionality in detail
=end
puts "Hello, World!"🏷️ Naming Conventions
Variable Naming
Ruby uses snake_case naming convention:
# Correct variable naming
first_name = "Zhang"
last_name = "San"
full_name = first_name + last_name
user_age = 25
is_student = true
# Not recommended naming
firstName = "Zhang" # camelCase (JavaScript style)
FirstName = "Zhang" # PascalCase (not for variables)Constant Naming
Constants use uppercase letters and underscores:
# Constant naming
PI = 3.14159
MAX_SIZE = 100
DEFAULT_NAME = "Anonymous User"
# Class names use PascalCase
class UserAccount
# Class-related code
endMethod Naming
Method names use snake_case, ending with ? for boolean returns and ! for dangerous operations:
# Regular method
def calculate_sum(a, b)
a + b
end
# Method that returns boolean
def is_adult?(age)
age >= 18
end
# Dangerous operation method (may modify original object)
def remove_user!
# Code to remove user
end🔤 Strings and Output
String Definition
Ruby supports multiple ways to define strings:
# Single-quoted strings (no escape sequence or interpolation parsing)
name = 'Zhang San'
message = 'Hello\nWorld' # \n will not be parsed as newline
# Double-quoted strings (parse escape sequences and interpolation)
name = "Li Si"
age = 25
message = "Hello, #{name}! You are #{age} years old."
greeting = "Hello\nWorld" # \n will be parsed as newline
# Multi-line string
poem = <<~TEXT
Moonlight before my bed,
Perhaps frost on the ground.
Lift my head and see the moon,
Lower my head and think of home.
TEXTOutput Statements
# puts - output and newline
puts "Hello, World!"
puts "Ruby", "Programming" # Can output multiple values
# print - output without newline
print "Hello, "
print "World!\n"
# p - output object's debug information
p "Hello, World!" # Output: "Hello, World!"
arr = [1, 2, 3]
p arr # Output: [1, 2, 3]🧮 Expressions and Operators
Basic Operators
# Arithmetic operators
result = 10 + 5 # Addition: 15
result = 10 - 5 # Subtraction: 5
result = 10 * 5 # Multiplication: 50
result = 10 / 5 # Division: 2
result = 10 % 3 # Modulo: 1
result = 2 ** 3 # Exponentiation: 8
# Comparison operators
result = 10 > 5 # Greater than: true
result = 10 < 5 # Less than: false
result = 10 >= 5 # Greater than or equal: true
result = 10 <= 5 # Less than or equal: false
result = 10 == 5 # Equal: false
result = 10 != 5 # Not equal: true
# Logical operators
result = true && false # And: false
result = true || false # Or: true
result = !true # Not: falseAssignment Operators
# Basic assignment
x = 10
# Compound assignment
x += 5 # Equivalent to x = x + 5
x -= 3 # Equivalent to x = x - 3
x *= 2 # Equivalent to x = x * 2
x /= 4 # Equivalent to x = x / 4
x %= 3 # Equivalent to x = x % 3🔄 Control Structure Basics
Conditional Statements
# if statement
age = 18
if age >= 18
puts "You are an adult"
end
# if-else statement
if age >= 18
puts "Adult"
else
puts "Minor"
end
# if-elsif-else statement
if age < 13
puts "Child"
elsif age < 18
puts "Teenager"
else
puts "Adult"
endLoop Statements
# while loop
counter = 0
while counter < 5
puts "Counter: #{counter}"
counter += 1
end
# for loop
for i in 1..5
puts "Number: #{i}"
end
# each iterator (recommended)
(1..5).each do |i|
puts "Number: #{i}"
end📦 Data Structure Basics
Arrays
# Create arrays
fruits = ["Apple", "Banana", "Orange"]
numbers = [1, 2, 3, 4, 5]
# Access array elements
first_fruit = fruits[0] # "Apple"
last_number = numbers[-1] # 5
# Array operations
fruits.push("Grape") # Add element
fruits << "Strawberry" # Add element (shorthand)
fruits.pop # Remove last elementHashes
# Create hashes
person = {
"name" => "Zhang San",
"age" => 25,
"city" => "Beijing"
}
# Using symbols as keys (recommended)
person = {
name: "Zhang San",
age: 25,
city: "Beijing"
}
# Access hash values
name = person[:name] # "Zhang San"
age = person[:age] # 25
# Modify hashes
person[:age] = 26
person[:job] = "Programmer"🎯 Method Definition
Basic Methods
# Method without parameters
def greet
puts "Hello!"
end
# Method with parameters
def greet_person(name)
puts "Hello, #{name}!"
end
# Method with default parameters
def greet_with_default(name = "Friend")
puts "Hello, #{name}!"
end
# Call methods
greet
greet_person("Li Si")
greet_with_default
greet_with_default("Wang Wu")Return Values
# Explicit return
def add(a, b)
return a + b
end
# Implicit return (returns last expression value)
def multiply(a, b)
a * b # Automatically returns result
end
# Multiple return values
def get_name_and_age
["Zhang San", 25]
end
name, age = get_name_and_age🧱 Classes and Objects Basics
Simple Class Definition
# Define class
class Person
# Constructor
def initialize(name, age)
@name = name # Instance variable
@age = age
end
# Instance method
def introduce
puts "I am #{@name}, I am #{@age} years old"
end
end
# Create object
person = Person.new("Zhang San", 25)
person.introduce # Output: I am Zhang San, I am 25 years old🔧 Practical Tips
Parallel Assignment
# Swap variable values
a, b = 1, 2
a, b = b, a # a=2, b=1
# Multiple assignment
x, y, z = 10, 20, 30
# Array destructuring
first, *rest = [1, 2, 3, 4, 5]
# first = 1, rest = [2, 3, 4, 5]Conditional Assignment
# Assign only when variable is undefined
name ||= "Default Name"
# Ternary operator
status = age >= 18 ? "Adult" : "Minor"📝 Practice Examples
Simple Calculator
class Calculator
def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
def multiply(a, b)
a * b
end
def divide(a, b)
if b == 0
puts "Error: Divisor cannot be zero"
return nil
end
a / b
end
end
# Use calculator
calc = Calculator.new
puts "10 + 5 = #{calc.add(10, 5)}"
puts "10 - 5 = #{calc.subtract(10, 5)}"
puts "10 * 5 = #{calc.multiply(10, 5)}"
puts "10 / 5 = #{calc.divide(10, 5)}"User Information Management
class UserManager
def initialize
@users = []
end
def add_user(name, age)
user = {
name: name,
age: age,
id: @users.length + 1
}
@users.push(user)
puts "User #{name} has been added"
end
def list_users
if @users.empty?
puts "No users yet"
return
end
puts "User list:"
@users.each do |user|
puts "ID: #{user[:id]}, Name: #{user[:name]}, Age: #{user[:age]}"
end
end
end
# Use user manager
manager = UserManager.new
manager.add_user("Zhang San", 25)
manager.add_user("Li Si", 30)
manager.list_users🎯 Syntax Summary
Essential Syntax to Master
- Variable Naming: Use snake_case
- String Interpolation: Use
#{}to insert variables in double-quoted strings - Code Blocks: Use
do...endor{}to define - Method Calls: Don't require parentheses (optional)
- Return Values: Methods automatically return the last expression value
Recommended Coding Style
- Indentation: Use 2 spaces
- Line Length: No more than 80 characters per line
- Blank Lines: Use blank lines between logical blocks
- Comments: Add comments for complex logic
📚 Next Steps
After mastering Ruby basic syntax, it is recommended to continue learning:
- Ruby Data Types - Deep dive into Ruby's various data types
- Ruby Variables - Learn variable scope and lifecycle
- Ruby Operators - Master more operators
- Ruby Conditional Statements - Learn complex conditional control structures
Continue your Ruby learning journey!