[Ruby] 5장 클래스와 객체 지향 프로그래밍

1. 클래스와 객체 지향 프로그래밍

Ruby는 객체 지향 프로그래밍(Object-Oriented Programming, OOP)을 지원하는 프로그래밍 언어로, 클래스와 객체를 중심으로 설계된 언어입니다. 먼저 클래스의 정의부터 살펴보겠습니다.


2. 클래스 정의

클래스는 객체를 생성하기 위한 청사진(템플릿)으로 Ruby에서는 class 키워드를 사용해 클래스를 정의합니다.

class Profile
  # 초기화 메서드
  def initialize(name, age, job)
   @name = name # 인스턴스 변수 
   @age = age 
   @job = job
  end 

# 메서드 정의
def info 
 puts "#{@name}은 #{@age}세이고, 직업은 #{@job}입니다."
end

def into 
   puts "이름: #{@name}, 나이: #{@age}, 직업: #{@job}"
end
end

2.객체 생성

클래스를 기반으로 객체를 생성할 수 있습니다, new 메서드를 사용해 객체를 인스턴스화합니다.

person = Profile.new("John", 30, "Front-end Developer")
person.into 
person.info

3. 인스턴스 변수와 메서드

  • 인스턴스 변수: 객체의 상태를 저장하는 변수로, @ 기호로 시작
  • 메서드: 객체가 수행할 수 있는 동작을 정의

4. 상속

Ruby에서 클래스가 다른 클래스의 속성과 메서드를 상속받을 수 있습니다.

class Game 
  def type 
     puts "장르: 액션 어드벤쳐"
  end
end 

class Zelda < Game 
   def type
     puts "플랫폼: Nintendo switch"
   end 
  end 

my_name = Game.new  # 장르 : 액션 어드벤쳐
my_name.type
my_game = Zelda.new  # 플랫폼: Nintendo switch
my_game.type

5. 다형성

다형성은 같은 메서드 이름이 다양한 객체에 다르게 동작할 수 있는 OOP의 특징입니다.

class Game 
  def speak 
      "Square Enix 3대 주력 게임: "
  end 
end 

class FF < Game 
  def speak 
     "Final Fantasy"
  end
end

class KH < Game 
  def speak
     "Kingdom Hearts"
  end
end 

class DQ < Game 
  def speak 
    "Dragon Quest"
  end 
end 


def game_speak(game)
  puts game.speak 
end 

my_game = FF.new 
my_game2 = KH.new 
my_game3 = DQ.new 

game_speak(my_game) # Final Fantasy
game_speak(my_game2) # Kingdom Hearts

6. 모듈

모듈은 관련된 메서드와 상수를 그룹화하여 재사용할 수 있는 방법으로, 클래스와 믹스인(Mixin)으로 사용되며, 여러 클래스에서 공통적으로 사용할 메서드를 정의할 수 있습니다.

module Running
  def run
    puts "러닝 중 입니다."
  end 
end

class Speed 
  include Running
end 

class Marathon
  include Running 
end 

jiwon = Speed.new 
jiwon.run # 러닝 중 입니다.

james = Marathon.new
james.run # 러닝 중 입니다.

 

위 예제에 Running 모듈은 run 메서드를 정의하고, Speed와 Marathon 클래스에서 이 모듈을 포함해 사용할 수 있습니다. 이를 통해 코드의 중복을 줄여, 유지보수성을 높일 수 있습니다.


 

 

GitHub - set-up-init/ruby-tutorial-tistory: https://thinky.tistory.com/category/Back-End/Ruby

https://thinky.tistory.com/category/Back-End/Ruby. Contribute to set-up-init/ruby-tutorial-tistory development by creating an account on GitHub.

github.com

 

LIST