# **Ruby의 객체지향 프로그래밍(OOP) 개념과 활용** Ruby는 순수 객체지향 언어(Object-Oriented Language)다. **모든 것이 객체**이며, 객체는 **클래스(Class)**에서 생성된다. 이번 글에서는 객체지향 프로그래밍(OOP)의 핵심 개념과 Ruby에서의 활용 방법을 설명한다. --- ## **1. 객체(Object)란?** 객체는 **상태(데이터)와 행동(메서드)**을 가진 독립적인 단위다. 예를 들어, 자동차 객체를 생각해보자. - **상태(속성, 데이터)**: 색상, 속도, 브랜드 - **행동(메서드)**: 가속, 감속, 방향 전환 Ruby에서는 모든 것이 객체이므로 숫자, 문자열, 배열도 객체다. ```ruby puts 10.class # Integer puts "Ruby".class # String puts [1, 2, 3].class # Array ``` --- ## **2. 클래스(Class)와 객체 생성** 클래스는 객체를 만들기 위한 **설계도(템플릿)**이다. ### **2.1. 클래스 정의** ```ruby class Car end ``` ### **2.2. 객체(인스턴스) 생성** `new` 메서드를 사용해 클래스로부터 객체를 생성할 수 있다. ```ruby my_car = Car.new puts my_car.class # Car ``` --- ## **3. 인스턴스 변수와 메서드** 클래스 내부에는 **속성(인스턴스 변수, `@변수명`)과 동작(메서드)**을 정의할 수 있다. ```ruby class Car def initialize(brand, color) @brand = brand # 인스턴스 변수 @color = color end def info puts "브랜드: #{@brand}, 색상: #{@color}" end end car1 = Car.new("Tesla", "Red") car2 = Car.new("BMW", "Blue") car1.info # "브랜드: Tesla, 색상: Red" car2.info # "브랜드: BMW, 색상: Blue" ``` ### **3.1. `initialize` 메서드** - 객체가 생성될 때 자동으로 호출되는 **생성자(constructor)**다. - `@변수명`을 사용해 객체 내부에서 데이터를 저장할 수 있다. --- ## **4. 접근자 메서드 (Getter, Setter)** Ruby에서는 객체의 속성을 직접 접근하지 않고, **메서드를 통해 접근하는 것이 일반적**이다. ```ruby class Car def initialize(brand, color) @brand = brand @color = color end # Getter (값을 반환) def brand @brand end # Setter (값을 변경) def color=(new_color) @color = new_color end end car = Car.new("Tesla", "Red") puts car.brand # "Tesla" car.color = "Blue" # Setter 사용 ``` Ruby에서는 이러한 Getter/Setter를 간편하게 정의할 수 있도록 `attr_accessor`, `attr_reader`, `attr_writer`를 제공한다. ```ruby class Car attr_accessor :brand, :color # Getter + Setter 자동 생성 def initialize(brand, color) @brand = brand @color = color end end car = Car.new("BMW", "White") puts car.brand # "BMW" car.color = "Black" puts car.color # "Black" ``` - `attr_reader :변수명` → 읽기 전용(Getter만) - `attr_writer :변수명` → 쓰기 전용(Setter만) - `attr_accessor :변수명` → 읽기 + 쓰기 --- ## **5. 클래스 메서드와 클래스 변수** ### **5.1. 클래스 변수(`@@`)** 클래스 전체에서 공유되는 변수다. ```ruby class Car @@count = 0 # 클래스 변수 def initialize(brand, color) @brand = brand @color = color @@count += 1 # 생성될 때마다 증가 end def self.total_cars @@count end end Car.new("Tesla", "Red") Car.new("BMW", "Blue") puts Car.total_cars # 2 ``` ### **5.2. 클래스 메서드 (`self.method_name`)** 클래스 자체에서 호출하는 메서드다. ```ruby class Car def self.info puts "자동차 클래스입니다." end end Car.info # "자동차 클래스입니다." ``` --- ## **6. 상속(Inheritance)** 한 클래스가 다른 클래스를 상속받아 기능을 확장할 수 있다. ```ruby class Vehicle def move puts "이동 중..." end end class Car < Vehicle end car = Car.new car.move # "이동 중..." ``` ### **6.1. `super` 키워드** 부모 클래스의 메서드를 호출할 때 사용한다. ```ruby class Vehicle def initialize(type) @type = type end def info puts "종류: #{@type}" end end class Car < Vehicle def initialize(brand, color) super("자동차") # 부모 클래스 생성자 호출 @brand = brand @color = color end def info super # 부모 클래스의 info 호출 puts "브랜드: #{@brand}, 색상: #{@color}" end end car = Car.new("Tesla", "Red") car.info ``` 출력 결과: ``` 종류: 자동차 브랜드: Tesla, 색상: Red ``` --- ## **7. 모듈(Module)과 믹스인(Mixin)** Ruby는 다중 상속을 지원하지 않지만, **모듈(Module)**을 사용해 기능을 추가할 수 있다. ### **7.1. 모듈 정의** ```ruby module Drivable def drive puts "운전 중..." end end ``` ### **7.2. 모듈 포함 (`include`)** `include`를 사용하면 인스턴스 메서드로 추가된다. ```ruby class Car include Drivable end car = Car.new car.drive # "운전 중..." ``` ### **7.3. 모듈 확장 (`extend`)** `extend`를 사용하면 클래스 메서드로 추가된다. ```ruby class Car extend Drivable end Car.drive # "운전 중..." ``` --- ## **8. 마무리** Ruby의 객체지향 프로그래밍(OOP)은 코드의 재사용성과 유지보수성을 높이는 강력한 개념이다. - **클래스(Class)와 객체(Object)** → 객체는 클래스로부터 생성됨 - **인스턴스 변수와 메서드** → `@변수`로 속성 저장, 메서드로 동작 정의 - **Getter/Setter** → `attr_accessor`로 간단하게 정의 가능 - **클래스 변수/메서드** → `@@변수`, `self.메서드` - **상속(Inheritance)** → `class 자식클래스 < 부모클래스` - **모듈(Module)과 믹스인(Mixin)** → `include`, `extend`로 기능 추가 이제 Ruby의 객체지향 개념을 활용하여 더욱 효율적인 프로그램을 만들어보자!