Ruby 文件处理和系统命令

发布: (2025年12月31日 GMT+8 12:41)
2 min read
原文: Dev.to

Source: Dev.to

打开文件并读取

File.open('p014constructs.rb', 'r') do |f1|
  while line = f1.gets
    puts line
  end
end

写入文件

File.open('test.rb', 'w') do |f2|
  f2.puts "Created by Satish\nThank God!"
end

指定编码打开文件

File.open('p014constructs.rb', 'r:UTF-16LE:UTF-8') do |f1|
  # ...
end

目录遍历

require 'find'

Find.find('./') do |f|
  type = case
         when File.file?(f) then "F"
         when File.directory?(f) then "D"
         else "?"
         end
  puts "#{type}: #{f}"
end

移动文件指针

f = File.new("hellousa.rb")

# SEEK_CUR - 相对当前位置移动
# SEEK_END - 相对文件末尾移动(使用负数值)
# SEEK_SET - 移动到绝对位置
f.seek(12, IO::SEEK_SET)
print f.readline
f.close

加载和require文件

# 每次执行文件时都会包含。
load 'filename.rb'

# 只加载一次文件(可省略.rb扩展名)
require 'filename'

# 使用相对路径加载文件。
require_relative 'p030motorcycle'

执行系统命令

puts `ls`

# 返回处理是否成功的 true/false。
system("pwd")

查看环境变量

ENV.each { |k, v| puts "#{k}: #{v}" }
Back to Blog

相关文章

阅读更多 »

U-Groovy

Groovy – 能力简要概述 我在 Jenkins 流水线中使用 Groovy 已有相当长的时间。现在我正更多地转向…

Ruby 异常处理与正则表达式

异常处理 在 Ruby 中查看抛出和处理异常的基本方法。 ruby def raise_exception puts 'I am before the raise.' raise 'An error has occured' puts 'I am after the raise' 执行…