1. 变量:
# 定义变量
name = "John"
age = 30
# 动态类型
name = 42
2. 数据类型:
# 基本数据类型
integer = 42
float = 3.14
string = "Hello, Ruby!"
boolean = true
# 符号(Symbol)
symbol = :example
3. 控制流:
# 条件语句
if condition
# code
elsif another_condition
# code
else
# code
end
# 三元运算符
result = condition ? "true_value" : "false_value"
# 循环
while condition
# code
end
until condition
# code
end
for i in 1..5
# code
end
# 迭代器
[1, 2, 3].each do |number|
puts number
end
4. 方法定义:
# 定义方法
def greet(name)
puts "Hello, #{name}!"
end
# 调用方法
greet("Alice")
5. 类与对象:
# 定义类
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def say_hello
puts "Hello, #{@name}!"
end
end
# 创建对象
person = Person.new("John", 30)
# 访问属性和调用方法
puts person.name
puts person.age
person.say_hello
6. 模块和命名空间:
# 定义模块
module MyModule
def my_method
puts "This is a module method."
end
end
# 使用模块
class MyClass
include MyModule
end
my_object = MyClass.new
my_object.my_method
7. 异常处理:
begin
# code that might raise an exception
rescue SomeException => e
puts "Caught an exception: #{e.message}"
else
puts "No exception occurred."
ensure
# code that will be executed no matter what
end
8. 文件操作:
# 打开文件
file = File.open("example.txt", "r")
# 读取文件内容
contents = file.read
puts contents
# 关闭文件
file.close
这只是 Ruby 语法的一小部分,但涵盖了一些基本的概念。Ruby 是一门非常灵活的语言,支持函数式编程、元编程等高级特性。
转载请注明出处:http://www.pingtaimeng.com/article/detail/13419/Ruby