기초
변수 & 타입
Ruby는 동적 타입 언어입니다—변수에 타입 선언이 필요 없습니다. 타입을 검사하려면 .class를, 타입 확인에는 is_a?를 사용하세요. 숫자와 불리언을 포함한 모든 것이 객체입니다.
name = "Alice" # string
age = 30 # integer
pi = 3.14 # float
is_dev = true # boolean
nums = [1, 2, 3] # array
puts name.class # String
puts age.is_a?(Integer) # trueSymbol
Symbol(:name)은 불변이며 인턴된 문자열입니다—메모리에 하나의 사본만 존재합니다. 해시 키, 메서드 이름, 내용보다 식별성이 중요한 식별자에 사용하세요. 반복 사용 시 문자열보다 메모리 효율적입니다.
status = :active
puts status.class # Symbol
puts status.to_s # "active"
# Symbols are immutable, reusable strings
hash = { name: "Alice", status: :active }
puts hash[:status] # activeNil & 진릿값
Ruby에서는 nil과 false만 거짓입니다—나머지 모든 것(0, '', [] 포함)은 참입니다. 이는 0이 거짓인 많은 언어와 다릅니다. 기본값에는 ||를, nil 확인에는 nil?을 사용하세요.
x = nil
puts x.nil? # true
puts x || "default" # default
# Only nil and false are falsy; 0 and "" are truthy!
puts 0 ? "truthy" : "falsy" # truthy
puts "" ? "truthy" : "falsy" # truthy
puts nil ? "truthy" : "falsy" # falsy타입 변환
to_i/to_s/to_f는 관대한 변환입니다(실패 시 0 반환). Integer()/Float()는 엄격합니다(ArgumentError 발생). 검증이 필요할 때는 엄격한 변환을, 우아한 저하를 원할 때는 관대한 변환을 사용하세요.
puts "42".to_i # 42
puts 42.to_s # "42"
puts "3.14".to_f # 3.14
puts 3.14.to_i # 3
puts "abc".to_i # 0 (no error)
puts Integer("42") # 42 (raises if invalid)문자열 보간
큰따옴표 문자열은 #{expr} 보간을 지원합니다—모든 Ruby 표현식을 넣을 수 있습니다. 작은따옴표 문자열은 리터럴입니다(\\와 \'를 제외한 보간이나 이스케이프 없음). 보간이나 이스케이프 시퀀스가 필요할 때 큰따옴표를 사용하세요.
name = "Alice"
age = 30
puts "Name: #{name}, Age: #{age}"
puts "5 + 3 = #{5 + 3}"
puts "Upper: #{name.upcase}"
# Single quotes don't interpolate
puts 'No #{name} here' # No #{name} here문자열
일반적인 문자열 메서드
Ruby 문자열은 풍부한 메서드를 가집니다. 대부분 새 문자열을 반환합니다(Ruby에서 문자열은 가변입니다). 제자리 수정을 위해 ! 변형(upcase!, gsub!)을 사용하세요—이들은 수신자를 수정하고 변경이 없으면 nil을 반환합니다.
s = "Hello, World"
puts s.length # 12
puts s.upcase # HELLO, WORLD
puts s.downcase # hello, world
puts s.reverse # dlroW ,olleH
puts s.split(", ") # ["Hello", "World"]
puts s.gsub("o", "0") # Hell0, W0rld문자열 변경 (Bang 메서드)
!로 끝나는 메서드는 객체를 제자리에서 수정하며 종종 더 효율적입니다. 변경이 없으면 nil을 반환할 수 있습니다. 복사본 생성을 피하고 싶을 때 사용하지만, 부작용에 주의하세요.
s = "hello"
s.upcase! # s is now "HELLO"
s.gsub!(/L/, "1") # s is now "HE11O"
puts s # HE11O
# Bang methods modify in-place; use with caution
arr = [3, 1, 2]
arr.sort! # arr is now [1, 2, 3]Heredoc & 여러 줄
Heredoc(<<TEXT ... TEXT)이 여러 줄 문자열을 생성합니다. <<~(물결표 heredoc)이 공통 선행 공백을 제거하여 코드를 깔끔하게 합니다. SQL 쿼리, HTML 템플릿, 긴 메시지에 유용합니다.
text = <<~HEREDOC
Hello,
World!
Indentation is stripped.
HEREDOC
puts text
# <<~ strips leading whitespace (Ruby 2.3+)
# <<HEREDOC preserves indentation포맷팅 (sprintf)
% 연산자나 format/sprintf로 C 스타일 문자열 포맷팅을 사용하세요. %-10s는 10자에서 왼쪽 정렬, %08.2f는 8자로 0 채우기(소수점 2자)입니다. 표 형식 출력과 고정 너비 포맷팅에 유용합니다.
puts sprintf("%s is %d", "Alice", 30)
puts "%-10s|%5d" % ["Name", 42]
puts format("%.2f", 3.14159) # 3.14
puts "%08.2f" % 3.14 # 00003.14
# %s string, %d integer, %f float문자열 연결
+는 새 문자열을 생성하고, <<는 제자리에서 추가합니다(문자열 빌드에 더 효율적). *는 문자열을 반복합니다. join이 배열 요소를 구분자와 결합합니다. 성능을 위해 반복되는 +보다는 <<나 join을 선호하세요.
s1 = "Hello" + ", " + "World"
s2 = ["a", "b", "c"].join("-") # a-b-c
s3 = "Hello"
s3 << " " << "World" # in-place append
s4 = "x" * 3 # xxx (repetition)
puts s1, s2, s3, s4데이터 구조
배열
배열은 순서가 있고 0부터 시작하며 혼합 타입을 가질 수 있습니다. <<와 push가 끝에 추가합니다. 멤버십에는 include?를, 합계에는 sum을 사용하세요. 배열은 가변입니다—불변으로 만들려면 freeze를 사용하세요.
nums = [1, 2, 3, 4, 5]
nums.push(6) # [1,2,3,4,5,6]
nums << 7 # same as push
nums[0] = 0
puts nums.first # 0
puts nums.length # 7
puts nums.sum # 28
puts nums.include?(3) # true해시
해시는 키-값 사전입니다. Symbol 키(name:)이 관용적이고 효율적입니다. 존재 확인에는 key?, 안전한 접근에는 fetch(누락 시 발생), 일괄 업데이트에는 transform_values를 사용하세요.
user = { name: "Alice", age: 30 }
user[:email] = "[email protected]"
puts user[:name] # Alice
puts user.key?(:name) # true
user.each { |k, v| puts "#{k}: #{v}" }
puts user.values # ["Alice", 30, "[email protected]"]
puts user.transform_values(&:to_s)범위
'..'는 끝을 포함하고, '...'는 끝을 제외합니다. 범위는 지연 평가되며 큰 시퀀스에 메모리 효율적입니다. 반복, 슬라이싱, 시퀀스 생성에 유용합니다. Comparable 타입과 함께 사용할 수 있습니다.
(1..5).each { |n| puts n } # 1 2 3 4 5
puts (1...5).to_a # [1, 2, 3, 4]
puts (1..10).select(&:even?) # [2, 4, 6, 8, 10]
puts ('a'..'e').include?('c') # true
puts (1..5).map { |n| n ** 2 } # [1, 4, 9, 16, 25]Enumerable 메서드
Enumerable은 Ruby의 가장 강력한 mixin입니다—map, select, reject, reduce, find, group_by, sort_by 등. { |x| x.method }의 약어로 &:method를 사용하세요. 이를 통해 표현적인 데이터 변환 파이프라인이 가능합니다.
nums = [1, 2, 3, 4, 5]
puts nums.map { |n| n * 2 }.inspect # [2,4,6,8,10]
puts nums.select(&:even?).inspect # [2, 4]
puts nums.reject(&:odd?).inspect # [2, 4]
puts nums.reduce(0) { |sum, n| sum + n } # 15
puts nums.find { |n| n > 3 } # 4
puts nums.group_by(&:even?).inspect # {false=>[1,3,5], true=>[2,4]}집합 (Set)
Set('set' 라이브러리에서)은 O(1) 조회로 고유한 요소를 저장합니다. 중복 제거와 집합 연산(합집합, 교집합, 차 집합)에 사용하세요. 배열이 필요할 때 to_a로 변환합니다. 'set' require가 필요합니다.
require 'set'
a = Set.new([1, 2, 3])
b = Set.new([3, 4, 5])
puts a.union(b).to_a.inspect # [1,2,3,4,5]
puts a.intersection(b).to_a.inspect # [3]
puts a.subtract([1]).to_a.inspect # [2, 3]
puts a.subset?(Set.new([1,2,3,4])) # true
a.add(6)제어 흐름
If / Elsif / Unless
if/elsif/else는 표준 분기입니다. unless는 if의 반대입니다(조건이 거짓일 때 실행). 수정자 형태(statement if condition)는 한 줄 가드에 관용적입니다—간단한 경우 가독성을 향상시킵니다.
score = 85
if score >= 90
puts "A"
elsif score >= 80
puts "B"
else
puts "C"
end
# Modifier form
puts "Pass" if score >= 60
puts "Fail" unless score >= 60Case (When)
case/when은 매칭에 ===를 사용하여 범위, 클래스, 정규식을 가능하게 합니다. 여러 값을 쉼표로 구분하세요. then은 한 줄 본문을 허용합니다. 대상 없이 case는 더 깔끔한 if/elsif 체인처럼 작동합니다.
grade = "B"
case grade
when "A" then puts "Excellent"
when "B", "C" then puts "Good"
when "D".."F" then puts "Poor"
else puts "Unknown"
end
# Case without value = multi-condition if
case
when score > 90 then puts "Top"
when score > 60 then puts "Pass"
endWhile / Until / Loop
while은 참일 때 실행, until은 참일 때까지 실행(거짓인 동안)합니다. loop는 무한합니다—종료하려면 break를 사용하세요. 컬렉션에는 while보다 반복자(each, map)를 선호하세요—더 관용적이고 오류가 적습니다.
count = 0
while count < 3
puts count
count += 1
end
# until = opposite of while
n = 3
until n == 0
puts n
n -= 1
end
# Infinite loop with break
loop do
puts "forever"
break if rand > 0.8
end반복자 (Each/Times/Upto)
Ruby의 반복자는 for 루프보다 관용적입니다. 카운팅에는 times, 범위에는 upto/downto, 인덱스+값에는 each_with_index를 사용하세요. step이 증분을 제어합니다. 이것들이 Ruby 반복의 근간입니다.
3.times { |i| puts i } # 0 1 2
1.upto(3) { |n| puts n } # 1 2 3
3.downto(1) { |n| puts n } # 3 2 1
[1,2,3].each_with_index do |n, i|
puts "#{i}: #{n}"
end
(1..3).step(1) { |n| puts n } # 1 2 3Break / Next / Redo
next는 다음 반복으로 건너뛰고(continue와 같음), break는 루프를 조기 종료합니다. break는 블록에서 값을 반환할 수 있습니다. redo는 조건을 다시 확인하지 않고 현재 반복을 다시 시작합니다—거의 사용되지 않습니다.
[1, 2, 3, 4, 5].each do |n|
next if n.even? # skip even
break if n > 4 # stop at 5
puts n # prints 1, 3
end
# break value returns from the block
result = [1,2,3].each { |n| break n * 10 if n == 2 }
puts result # 20메서드 & 블록
메서드 정의
메서드는 def/end를 사용합니다. 키워드 인자(key:)가 많은 매개변수의 가독성을 향상시킵니다. *args는 추가 위치 인자를 배열로 모으고, **kwargs는 키워드 인자를 해시로 모읍니다. 기본값은 =를 사용합니다.
def greet(name, greeting: "Hello")
"#{greeting}, #{name}!"
end
puts greet("Alice") # Hello, Alice!
puts greet("Bob", greeting: "Hi") # Hi, Bob!
def add(*nums) # splat (variadic)
nums.sum
end
puts add(1, 2, 3, 4) # 10블록 & Yield
블록은 메서드에 전달되는 익명 코드 조각입니다. yield가 블록을 호출합니다. 블록은 Ruby 어디에나 있습니다(each, map 등). 메서드를 유연하게 만들려면 yield를 사용하세요—호출자가 동작을 제공합니다.
def repeat(n)
n.times { yield }
end
repeat(3) { puts "hi" } # prints hi 3 times
def with_result
yield(5)
end
puts with_result { |x| x * 2 } # 10Proc & Lambda
Proc과 lambda는 변수에 저장된 재사용 가능한 블록입니다. 주요 차이: lambda는 인자 수를 확인(불일치 시 발생)하고 자신에게만 반환; proc은 관대하고 둘러싼 메서드에서 반환합니다. 엄격한 동작에는 lambda를 선호하세요.
square = proc { |x| x * x }
puts square.call(5) # 25
puts square.(5) # 25 (shortcut)
double = lambda { |x| x * 2 }
puts double.call(5) # 10
# Lambda checks arity; Proc doesn't
# Lambda returns from itself; Proc returns from enclosing method메서드 객체 (&)
&:method가 메서드 이름을 Proc으로 변환합니다. 간단한 한 메서드 블록의 관용적 약어입니다: map { |s| s.to_i } 대신 map(&:to_i). 간단한 변환에 더 깔끔하고 가독성이 좋습니다.
nums = ["1", "2", "3"]
ints = nums.map(&:to_i) # [1, 2, 3]
puts ints.inspect
# &:to_i is shorthand for { |s| s.to_i }
names = ["alice", "bob"]
up = names.map(&:upcase) # ["ALICE", "BOB"]
puts up.inspect반환값
Ruby 메서드는 마지막으로 평가된 표현식을 암시적으로 반환합니다—명시적 return이 필요 없습니다. 조기 종료에 return을 사용하세요. 여러 값이 배열로 반환되고 분해될 수 있습니다. 이것이 코드를 간결하게 만듭니다.
def status(ok)
return "error" unless ok
"ok" # implicit return of last expression
end
puts status(true) # ok
puts status(false) # error
# Multiple assignment
def coords
return 1, 2 # returns [1, 2]
end
x, y = coords클래스 & OOP
클래스 & 인스턴스 변수
@var = 인스턴스 변수(객체별), @@var = 클래스 변수(공유). attr_accessor가 getter+setter 생성, attr_reader는 getter만, attr_writer는 setter만 생성합니다. self.method가 클래스 메서드를 정의합니다.
class Person
attr_accessor :name, :age
attr_reader :id
@@count = 0 # class variable
def initialize(name, age)
@name = name # instance variable
@age = age
@@count += 1
end
def self.count; @@count; end
end
p = Person.new("Alice", 30)
puts p.name, Person.count상속 & Super
<는 상속을 나타냅니다(단일 상속만). super가 부모의 현재 메서드 버전을 호출합니다. 부모 동작을 확장하려면 super(인자 전달 시 괄호, 같은 인자 전달 시 괄호 없이)를 사용하세요. Ruby는 단일 상속 + mixin을 사용합니다.
class Animal
def initialize(name); @name = name; end
def speak; "..."; end
end
class Dog < Animal
def speak; "#{@name}: Woof!"; end
end
class Puppy < Dog
def speak; "#{super} (small)"; end
end
puts Puppy.new("Rex").speak # Rex: Woof! (small)모듈 (Mixin)
모듈은 재사용 가능한 메서드를 그룹화합니다. include는 인스턴스 메서드 추가, extend는 클래스 메서드 추가. 이것이 Ruby의 다중 상속에 대한 해결책입니다. Enumerable이 유명한 mixin입니다—이를 include하고 each를 정의하면 map, select 등을 얻습니다.
module Walkable
def walk; "#{@name} is walking"; end
end
module Swimmable
def swim; "#{@name} is swimming"; end
end
class Duck
include Walkable # instance methods
extend Swimmable # class methods
def initialize(n); @name = n; end
end
puts Duck.new("Donald").walk # Donald is walking접근 제어
public(기본), private(명시적 수신자 없이만 호출 가능), protected(클래스 계층 내에서 호출 가능). 내부 헬퍼에는 private을, 같은 클래스 인스턴스 간 공유 메서드에는 protected를 사용하세요.
class BankAccount
def initialize(bal); @balance = bal; end
def deposit(amt); @balance += amt; end
def balance; @balance; end
private
def audit; "auditing..."; end
protected
def compare(other); @balance > other.balance; end
end
a = BankAccount.new(100)
puts a.balance # 100
# a.audit # Error: private methodSelf & 클래스 메서드
self는 현재 객체를 참조합니다. 클래스 본문 내에서 self는 클래스입니다—def self.method가 클래스 메서드를 정의합니다. 클래스 메서드는 클래스에서(Counter.total), 인스턴스 메서드는 인스턴스에서 호출합니다. alias_method가 메서드 별칭을 생성합니다.
class Counter
@@total = 0
def initialize; @@total += 1; end
def self.total; @@total; end
def self.reset!; @@total = 0; end
def instance_method; "I'm an instance"; end
alias_method :count, :instance_method
end
Counter.new; Counter.new
puts Counter.total # 2