Menu
Coddy logo textTech

인스턴스 변수

Coddy Ruby 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 3번째.

인스턴스 변수는 @로 시작하며 하나의 객체에 속합니다. initialize에 저장된 값은 해당 객체의 모든 메서드에서 계속 사용할 수 있고, 각 인스턴스는 자체 복사본을 가집니다:

class Dog
  def initialize(name)
    @name = name
  end

  def speak
    "#{@name} says Woof"
  end
end

rex = Dog.new("Rex")
bella = Dog.new("Bella")
puts rex.speak
puts bella.speak

출력:

Rex says Woof
Bella says Woof

메서드는 인스턴스 변수를 변경할 수 있으므로, 객체는 자신에게 일어난 일을 기억합니다. 객체의 인스턴스 변수들을 함께 객체의 상태라고 합니다:

class Counter
  def initialize
    @count = 0
  end

  def increment
    @count += 1
  end

  def report
    "count is #{@count}"
  end
end

clicks = Counter.new
clicks.increment
clicks.increment
puts clicks.report

출력:

count is 2

인스턴스 변수는 객체 외부에서 접근할 수 없습니다. 외부의 코드는 메서드만 호출할 수 있으므로, 값을 공유하려는 클래스는 그 값을 반환하는 메서드인 리더를 정의합니다:

class Dog
  def initialize(name)
    @name = name
  end

  def name
    @name
  end
end

rex = Dog.new("Rex")
puts rex.name
begin
  rex.age
rescue NoMethodError => e
  puts e.message
end

출력:

Rex
undefined method `age' for an instance of Dog

할당된 적이 없는 인스턴스 변수는 nil이며 오류를 발생시키지 않으므로, 철자가 틀린 이름을 사용해도 조용히 다른 빈 변수를 읽게 됩니다. instance_variables는 객체가 실제로 가지고 있는 변수를 나열합니다:

class Lamp
  def initialize
    @on = false
  end

  def status
    @onn.inspect
  end
end

lamp = Lamp.new
puts lamp.status
p lamp.instance_variables

출력:

nil
[:@on]
challenge icon

챌린지

쉬움

Pet 클래스를 완성하세요. initialize(name, species, age)는 세 값을 저장하고, birthday는 나이에 1년을 더하며, describe는 한 문장을 반환합니다. 이름이 Rex이고 종이 dog이며 나이가 3인 반려동물의 경우 Rex is a 3 year old dog가 반환됩니다.

제공된 코드는 처음 세 입력 줄(name, species, age)로 Pet을 생성하고, 네 번째 줄에 지정된 횟수만큼 birthday를 호출한 다음 describe를 출력합니다.

코드는 pet.rb에 작성하세요. main.rb에는 제공된 입력/출력 코드가 들어 있으며 수정할 수 없습니다.

직접 해보기

require_relative 'pet'

# 제공된 입력/출력 코드: 그대로 유지하세요
input = []
while (line = gets)
  input << line.chomp
end
pet = Pet.new(input[0], input[1], input[2].to_i)
input[3].to_i.times { pet.birthday }
puts pet.describe
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Ruby 컴파일러