Ruby 파일 처리와 시스템 명령

Published: (December 30, 2025 at 11:41 PM EST)
2 min read
Source: 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

Related posts

Read more »

U-Groovy

Groovy – A Short Summary of Its Capabilities I have been working with Groovy in Jenkins pipelines for an extended period of time. Now I’m moving more into the...

Ruby 기초 - 문법과 기본 개념

Ruby 프로그래밍 언어의 기본 문법과 개념을 알아봅니다. 파일 및 실행 ruby 파일 형식: 파일명.rb 실행 방법: ruby 파일명.rb 확장자가 rb가 아니어도 실행 가능 주석 ruby 한 줄 주석 =begin 여러 줄 주석 =end 줄바꿈 및 명령 구분 ruby 줄바꿈 puts...