Ruby 파일 처리와 시스템 명령

발행: (2025년 12월 31일 오후 01:41 GMT+9)
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

파일 로드와 요구

# 파일을 실행할 때마다 포함합니다.
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 – 그 기능에 대한 짧은 요약 나는 오랫동안 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.' end ``` 위 코드를 실행하면…