Kernel

Kernel

Kernel 모듈은 모든 객체가 기본적으로 사용할 수 있는 전역 메서드를 제공해요. puts, p, require, rand 같은 것들이 전부 Kernel의 인스턴스 메서드예요.

출처: Ruby 4.0 API

본문

KernelObject 클래스가 포함하는 모듈이라서 어디서든 메서드를 호출할 수 있어요. 여기서는 형 변환 메서드와 자주 쓰는 전역 메서드를 정리할게요.

형 변환 메서드 (Conversion)

Array(object) → object or new_array
Complex(real, imag = 0, exception: true) → complex or nil
Complex(s, exception: true) → complex or nil
Float(arg, exception: true) → float or nil
Hash(object) → object or new_hash
Integer(object, base = 0, exception: true) → integer or nil
Rational(x, y, exception: true) → rational or nil
Rational(arg, exception: true) → rational or nil
String(object) → object or new_string

객체를 해당 타입으로 변환해요. exception: false를 주면 변환 실패 시 예외 대신 nil을 돌려줘요. Integerbase로 진법을 지정할 수 있어요.

출력 메서드 (Output)

p(object) → obj
p(*objects) → array of objects
puts(*objects) → nil
print(*objects) → nil
printf(format_string, *objects) → nil
printf(io, format_string, *objects) → nil
putc(int) → int
sprintf(format_string, *objects) → string   # 형식화 문자열 반환 (format과 동일)

pinspect 결과를, puts는 줄바꿈을 붙여 출력해요. sprintf는 출력 대신 문자열로 돌려줘요.

입력 메서드 (Input)

readline(sep = $/, chomp: false) → string
readline(limit, chomp: false) → string
readline(sep, limit, chomp: false) → string
readlines(sep = $/, chomp: false, **enc_opts) → array
select(read_ios, write_ios = [], error_ios = [], timeout = nil) → array or nil

표준 입력에서 줄을 읽어요. readlines는 끝까지 줄 배열로 읽어요.

블록·프로시저 관련

block_given? → true or false
proc { |...| block } → a_proc
lambda { |...| block } → a_proc
iterator? → true or false
loop → an_enumerator
loop { ... }

proc/lambda로 블록을 프로시저 객체로 만들어요. loop는 무한 반복(break로 탈출). block_given?/iterator?는 블록이 주어졌는지 확인해요.

로딩·실행 관련

require_relative(string) → true or false
load(filename, wrap = false) → true
autoload(const, filename) → nil
autoload?(name, inherit = true) → String or nil
at_exit { block } → proc

require_relative는 현재 파일 기준 상대 경로로 파일을 로드해요. autoload는 상수가 처음 참조될 때 파일을 로드하도록 예약해요. at_exit는 프로그램 종료 시 실행할 블록을 등록해요.

객체 상태·추적 관련

__method__ → symbol          # 현재 실행 중인 메서드 이름
__callee__ → symbol          # 호출된(별칭 포함) 메서드 이름
__dir__ → string             # 현재 파일의 디렉터리
class → class
clone(freeze: nil) → an_object
frozen? → true or false
global_variables → array
local_variables → array
binding → a_binding
caller(start = 1, length = nil) → array or nil
caller(range) → array or nil
caller_locations(start = 1, length = nil) → array or nil  # Thread::Backtrace::Location

caller/caller_locations는 호출 스택 백트레이스를 돌려줘요.

난수·시그널·기타

rand(max = 0) → number
srand(number = Random.new_seed) → old_seed
sleep(secs = nil) → slept_secs
trap(signal, command) → obj
trap(signal) { ... } → obj
warn(*msgs, uplevel: nil, category: nil) → nil
test(char, path0, path1 = nil) → object
$-
chomp(string) → $_    # $_의 chomp
chop → $_
gsub(pattern, replacement) → $_
gsub(pattern) {|...| block } → $_
sub(pattern, replacement) → $_
sub(pattern) {|...| block } → $_

$ 계열 메서드(chomp, chop, gsub, sub)는 $_(마지막 입력 줄)을 대상으로 하는 특수 메서드예요.

그 외 유틸리티

tap {|x| block } → obj
then {|x| block } → an_object
open(path, mode = 'r', perm = 0666, **opts) → io or nil
open(path, mode = 'r', perm = 0666, **opts) {|io| ... } → obj
fork { ... } → integer or nil
fork → integer or nil
syscall(integer_callno, *arguments) → integer
callcc {|cont| block } → obj
set_trace_func(proc) → proc     # 실행 추적 콜백 설정
set_trace_func(nil) → nil
trace_var(symbol, cmd) → nil
trace_var(symbol) {|val| block } → nil

tap은 블록에 자기 자신을 넘기고 self를 그대로 돌려줘요. then은 블록 결과를 돌려줘요. fork는 자식 프로세스를 만들어요. callcc는 continuation(제어 흐름 재개)을 만들어요.