Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.
Ruby 概述
Ruby 是一种动态的、面向对象的编程语言,由日本程序员松本行弘(Yukihiro “Matz” Matsumoto)于1995年创建。Ruby 的设计哲学是:
开发者的快乐优先 : 让编程变得愉悦
最小惊讶原则 : 语言行为符合直觉
多范式编程 : 支持面向对象、函数式、命令式等多种编程范式
基础语法
变量和数据类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 name = "Alice" age = 30 pi = 3.14159 is_valid = true MAX_SIZE = 100 PI = 3.14159 status = :active direction = :north numbers = [1 , 2 , 3 , 4 , 5 ] mixed = [1 , "two" , 3.0 , :four ] person = { name: "Bob" , age: 25 , city: "NYC" } legacy_hash = { "name" => "Charlie" , "age" => 35 } range1 = 1 ..10 range2 = 1 ...10
控制结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 age = 18 if age >= 18 puts "Adult" elsif age >= 13 puts "Teenager" else puts "Child" end puts "Adult" if age >= 18 puts "Not adult" unless age >= 18 grade = 'B' case gradewhen 'A' puts "Excellent" when 'B' puts "Good" when 'C' puts "Average" else puts "Need improvement" end result = age >= 18 ? "Adult" : "Minor"
循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 i = 0 while i < 5 puts i i += 1 end i = 0 until i >= 5 puts i i += 1 end for i in 0 ..4 puts i end 5 .times do |i | puts i end [1 , 2 , 3 ].each do |num | puts num end person.each do |key, value | puts "#{key} : #{value} " end loop do puts "Infinite loop" break if some_condition end
面向对象编程
类和对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 class Person @@count = 0 attr_accessor :name , :age attr_reader :id attr_writer :password def initialize (name, age ) @name = name @age = age @id = @@count += 1 end def introduce "Hi, I'm #{@name } , #{@age } years old." end def self .total_count @@count end private def secret_method "This is private" end end person = Person .new("Alice" , 30 ) puts person.introduce puts person.name person.age = 31 puts Person .total_count
继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 class Animal attr_accessor :name def initialize (name ) @name = name end def speak "Some sound" end end class Dog < Animal def speak "Woof!" end def fetch "#{@name } is fetching the ball" end end class Cat < Animal def initialize (name, color ) super (name) @color = color end def speak "Meow!" end end dog = Dog .new("Buddy" ) puts dog.speak puts dog.fetch
模块(Modules)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 module Swimmable def swim "Swimming..." end end module Flyable def fly "Flying..." end end class Duck include Swimmable include Flyable def quack "Quack!" end end duck = Duck .new puts duck.swim puts duck.fly puts duck.quack module MyApp module Models class User end end end user = MyApp : :Models : :User .new
方法和块
方法定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 def greet (name ) "Hello, #{name} !" end def greet (name = "Guest" ) "Hello, #{name} !" end def sum (*numbers ) numbers.reduce(0 , :+ ) end puts sum(1 , 2 , 3 , 4 ) def create_user (name: , age: , email: nil ) { name: name, age: age, email: email } end create_user(name: "Alice" , age: 30 ) def add (a, b ) a + b end
块(Blocks)、Proc 和 Lambda
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 [1 , 2 , 3 ].each { |n | puts n } [1 , 2 , 3 ].each do |n | puts n * 2 end def my_method yield if block_given? end my_method { puts "Block executed" } my_proc = Proc .new { |x | x * 2 } puts my_proc.call(5 ) my_lambda = lambda { |x | x * 2 } my_lambda = ->(x) { x * 2 } puts my_lambda.call(5 )
常用方法和技巧
数组方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 arr = [1 , 2 , 3 , 4 , 5 ] arr.map { |x | x * 2 } arr.select { |x | x > 2 } arr.reject { |x | x > 2 } arr.find { |x | x > 2 } arr.reduce(0 ) { |sum, x | sum + x } arr.first arr.last arr.length arr.empty? arr.include ?(3 ) arr.reverse arr.sort arr.uniq
字符串方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 str = "Hello World" str.upcase str.downcase str.capitalize str.reverse str.length str.split str.include ?("World" ) str.gsub("World" , "Ruby" ) name = "Alice" "Hello, #{name} !" text = <<~HEREDOC This is a multi-line string with indentation removed HEREDOC
哈希方法
1 2 3 4 5 6 7 hash = { a: 1 , b: 2 , c: 3 } hash.keys hash.values hash.has_key?(:a ) hash.merge({ d: 4 }) hash.select { |k, v | v > 1 }
异常处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 begin result = 10 / 0 rescue ZeroDivisionError => e puts "Error: #{e.message} " rescue StandardError => e puts "Other error: #{e.message} " else puts "No errors" ensure puts "Always executed" end def validate_age (age ) raise ArgumentError , "Age must be positive" if age < 0 end class CustomError < StandardError ; end begin raise CustomError , "Something went wrong" rescue CustomError => e puts e.message end
文件操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 content = File .read("file.txt" ) File .readlines("file.txt" ).each do |line | puts line end File .write("file.txt" , "Hello, Ruby!" )File .open("file.txt" , "w" ) do |file | file.puts "Line 1" file.puts "Line 2" end File .open("file.txt" , "a" ) do |file | file.puts "Appended line" end File .exist?("file.txt" )File .directory?("path/to/dir" )
总结核心知识要点
语言特性
动态类型 : 无需声明变量类型,运行时确定
面向对象 : 一切皆对象,包括数字、字符串等基本类型
简洁语法 : 隐式返回、可选括号、符号表示
块和闭包 : 强大的代码块功能,支持 Proc 和 Lambda
核心语法示例
1. 变量和常量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 name = "Ruby" @instance_var = "instance" @@class_var = "class" $global_var = "global" CONSTANT = "immutable" status = :active
2. 集合操作
1 2 3 4 5 6 7 8 9 10 11 result = [1 , 2 , 3 , 4 , 5 ] .map { |x | x * 2 } .select { |x | x > 5 } .reduce(:+ ) person = { name: "Alice" , age: 30 } person.merge!(city: "NYC" ) person.transform_values { |v | v.to_s }
3. 面向对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class BankAccount attr_reader :balance def initialize (initial_balance = 0 ) @balance = initial_balance end def deposit (amount ) @balance += amount if amount > 0 end def withdraw (amount ) @balance -= amount if amount > 0 && amount <= @balance end end account = BankAccount .new(1000 ) account.deposit(500 ) account.withdraw(200 )
4. 模块和混入
1 2 3 4 5 6 7 8 9 10 11 12 13 module Logging def log (message ) puts "[#{Time .now} ] #{message} " end end class Application include Logging def run log "Application started" end end
5. 迭代器和块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 5 .times { |i | puts i }1 .upto(5 ) { |i | puts i }5 .downto(1 ) { |i | puts i }class MyCollection def initialize (data ) @data = data end def each @data .each { |item | yield item } end end collection = MyCollection .new([1 , 2 , 3 ]) collection.each { |item | puts item }
常用命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ruby script.rb irb gem install package_name gem list bundle install bundle exec ruby script.rb ruby test_file.rb rake test
最佳实践
遵循 Ruby 风格指南 : 使用 2 空格缩进,蛇形命名法
使用符号作为哈希键 : { name: "Alice" } 而不是 { "name" => "Alice" }
利用块和迭代器 : 避免使用传统 for 循环
使用 attr_accessor : 简化 getter/setter 定义
异常处理 : 只捕获需要处理的特定异常
使用 Bundler 管理依赖 : 通过 Gemfile 管理项目依赖
核心概念
Duck Typing : “如果它走起来像鸭子,叫起来像鸭子,那它就是鸭子”
元编程 : Ruby 强大的运行时代码生成能力
Mixin : 通过模块实现多重继承效果
开放类 : 可以重新打开和修改任何类(包括标准库)
块即闭包 : 块可以捕获外部作用域的变量
References