Ruby 是一种动态、反射和面向对象的编程语言,它以其简洁的语法和强大的功能而受到许多开发者的喜爱。以下是 Ruby 语言的一些基本语法:
1. 打印输出
puts "Hello, Ruby!"
变量赋值
x = 10
name = "John"
2. 数据类型
Ruby 有多种基本数据类型,包括整数、浮点数、字符串、数组、哈希(Hash)和符号(Symbol)。
number = 42 # 整数
float_number = 3.14 # 浮点数
greeting = "Hello" # 字符串
names = ["John", "Jane", "Foo"] # 数组
person = { name: "John", age: 30 } # 哈希
id = :user_id # 符号
3. 条件语句
age = 20
if age > 18
puts "You are an adult."
elsif age == 18
puts "You are an adult."
else
puts "You are a minor."
end
4. 循环
Ruby 中的循环包括 while
和 until
循环。
ruby
i = 0
while i < 5
puts i
i += 1
end
i = 0
until i >= 5
puts i
i += 1
end
5. 数组和迭代
numbers = [1, 2, 3, 4, 5]
numbers.each do |number|
puts number
end
6. 哈希(Hash)
person = { name: "John", age: 30 }
puts person[:name] # 输出 John
7. 方法定义
def greet(name)
puts "Hello, #{name}!"
end
greet("John")
8. 类和对象
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def greet
puts "Hello, my name is #{@name} and I am #{@age} years old."
end
end
person = Person.new("John", 30)
person.greet
9. 模块和混入
module Greeting
def say_hello
puts "Hello, world!"
end
end
class Person
include Greeting
end
person = Person.new
person.say_hello
10. 块(Block)
[1, 2, 3, 4].each { |number| puts number * 2 }
11. 文件操作
File.open("file.txt", "r") do |file|
while line = file.gets
puts line
end
end
Ruby 的语法简洁而强大,非常适合快速开发。