1. 标准输入与输出

输出到控制台

使用 putsprintp

puts "你好,世界!"  # 自动换行
print "你好,"       # 不换行
print "世界!\n"     # 手动换行
p "你好"            # 输出对象,带引号和换行:"你好"

输出:

你好,世界!
你好,世界!
"你好"

从控制台输入

使用 gets

print "请输入你的名字:"
name = gets.chomp  # chomp 移除末尾换行符
puts "你好,#{name}!"

运行示例:

请输入你的名字:张三
你好,张三!

2. 文件操作基础

Ruby 使用 File 类处理文件操作,需要包含文件路径和模式。

文件打开模式

模式说明
r只读(默认,从头开始)
w只写(覆盖文件)
a追加写(从末尾添加)
r+读写(从头开始)
w+读写(覆盖文件)
a+读写(从末尾添加)

3. 读取文件

读取整个文件

# 假设有个文件 "example.txt" 内容为:
# 你好
# 世界
content = File.read("example.txt")
puts content

输出:

你好
世界

逐行读取

  • each_line
  File.foreach("example.txt") do |line|
    puts "行:#{line.chomp}"
  end

输出:

  行:你好
  行:世界
  • readlines
  lines = File.readlines("example.txt", chomp: true)
  lines.each { |line| puts line }

输出:

  你好
  世界

打开文件并读取

File.open("example.txt", "r") do |file|
  while line = file.gets
    puts line
  end
end

输出:

你好
世界

4. 写入文件

覆盖写入

File.write("output.txt", "你好,Ruby!")
# 文件内容变为:你好,Ruby!

追加写入

File.open("output.txt", "a") do |file|
  file.puts "这是新的一行"
end
# 文件内容变为:
# 你好,Ruby!
# 这是新的一行

写入多行

lines = ["第一行", "第二行", "第三行"]
File.open("output.txt", "w") do |file|
  lines.each { |line| file.puts line }
end
# 文件内容:
# 第一行
# 第二行
# 第三行

5. 文件操作的异常处理

使用 rescue

begin
  content = File.read("nonexistent.txt")
rescue Errno::ENOENT => e
  puts "文件不存在:#{e.message}"
end

输出:

文件不存在:No such file or directory @ rb_sysopen - nonexistent.txt

检查文件是否存在

if File.exist?("example.txt")
  puts "文件存在"
else
  puts "文件不存在"
end

6. 中文支持示例

写入中文

File.open("greeting.txt", "w") do |file|
  file.puts "你好,世界!"
  file.puts "今天是 #{Time.now.strftime("%Y年%m月%d日")}"
end

文件内容:

你好,世界!
今天是 2025年03月22日

读取中文

File.foreach("greeting.txt") do |line|
  puts "读取:#{line.chomp}"
end

输出:

读取:你好,世界!
读取:今天是 2025年03月22日

7. 实践案例

案例 1:日志记录器

class Logger
  def initialize(filename)
    @filename = filename
  end

  def log(message)
    File.open(@filename, "a") do |file|
      file.puts "[#{Time.now}] #{message}"
    end
  end
end

logger = Logger.new("log.txt")
logger.log("程序启动")
logger.log("任务完成")

文件内容(示例):

[2025-03-22 10:15:30 +0800] 程序启动
[2025-03-22 10:15:31 +0800] 任务完成

案例 2:读取 CSV 文件

假设有个 data.csv 文件:

姓名,年龄
张三,25
李四,30

代码:

require 'csv'

CSV.foreach("data.csv", headers: true) do |row|
  puts "#{row['姓名']}:#{row['年龄']} 岁"
end

输出:

张三:25 岁
李四:30 岁

案例 3:文件备份

def backup_file(source, destination)
  if File.exist?(source)
    File.write(destination, File.read(source))
    puts "备份成功:#{source} -> #{destination}"
  else
    puts "源文件不存在"
  end
end

backup_file("example.txt", "example_backup.txt")

输出(假设文件存在):

备份成功:example.txt -> example_backup.txt

8. 文件路径操作

使用 FileDir

# 当前目录
puts Dir.pwd  # /home/user(示例)

# 文件名操作
puts File.basename("path/to/example.txt")  # example.txt
puts File.dirname("path/to/example.txt")   # path/to
puts File.extname("example.txt")           # .txt

# 列出目录内容
Dir.foreach(".") { |file| puts file }

路径拼接

path = File.join("path", "to", "file.txt")
puts path  # path/to/file.txt

9. 注意事项

  • 编码:Ruby 默认 UTF-8,确保文件和终端编码一致,避免中文乱码:
  File.open("test.txt", "w:UTF-8") { |f| f.puts "你好" }
  • 关闭文件:用块操作(如 File.open ... do)自动关闭文件,避免资源泄漏。
  • 权限:确保有读写权限,否则会抛出异常。

下一步

  • 练习:告诉我你想用文件做什么(读写日志、处理 CSV 等),我可以设计一个例子。
  • 问题解答:对文件操作有疑问吗?直接问我!
  • 深入学习:想了解文件流、Binary 操作或与数据库结合吗?我可以继续讲解。

你现在想做什么?写代码、问问题,还是其他?