1. 变量和数据类型:
# 变量赋值
name = "John"
age = 25
# 数据类型
string_var = "This is a string"
integer_var = 42
float_var = 3.14
boolean_var = true
2. 输出和输入:
# 输出
puts "Hello, #{name}!"
# 输入
print "Enter your age: "
user_age = gets.chomp.to_i
puts "You are #{user_age} years old."
3. 条件语句:
if age >= 18
puts "You are an adult."
else
puts "You are a minor."
end
4. 循环:
# 循环次数
5.times do
puts "This is a loop iteration."
end
# 数组迭代
fruits = ["apple", "banana", "orange"]
fruits.each do |fruit|
puts "I like #{fruit}s."
end
5. 函数和方法:
# 函数
def greet(name)
puts "Hello, #{name}!"
end
greet("Alice")
# 方法
string_var.upcase # 将字符串转为大写
integer_var.to_s # 将整数转为字符串
6. 数组和哈希:
# 数组
fruits = ["apple", "banana", "orange"]
# 哈希
person = { "name" => "John", "age" => 30 }
7. 类和对象:
class Dog
def initialize(name)
@name = name
end
def bark
puts "Woof, woof!"
end
def info
puts "#{@name} is a dog."
end
end
# 创建对象
my_dog = Dog.new("Buddy")
# 调用方法
my_dog.bark
my_dog.info
8. 异常处理:
begin
result = 10 / 0
rescue ZeroDivisionError
puts "Cannot divide by zero!"
end
9. 符号(Symbol):
符号是不可变的标识符,通常用于表示名字或标签。
my_symbol = :example
10. 块(Block):
块是一段可以被传递给方法的代码,常用于迭代或回调。
3.times do
puts "This is a block."
end
这只是Ruby语法的基础,Ruby还支持更多高级特性和语法糖,如模块、混入、DSL(领域特定语言)等。
转载请注明出处:http://www.zyzy.cn/article/detail/6443/Ruby