클래스 인스턴스 변수
Coddy Ruby 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 13번째.
클래스도 객체이므로 자체 인스턴스 변수를 가질 수 있습니다. @issued = 0은 self가 클래스인 클래스 본문에 있으며, 어떤 인스턴스에도 속하지 않고 클래스에 속합니다. 클래스 메서드는 이 변수를 읽고 변경합니다:
class Ticket
@issued = 0
def self.issue
@issued += 1
end
def self.issued
@issued
end
end
Ticket.issue
Ticket.issue
puts Ticket.issued출력:
2attr_accessor를 class << self 안에서 사용하면 클래스에 리더와 세터가 생성됩니다. 그러면 인스턴스는 self.class를 통해 클래스의 상태에 접근할 수 있습니다. 예를 들어 new가 생성하는 모든 객체의 수를 세려면 다음과 같습니다:
class Robot
@built = 0
class << self
attr_accessor :built
end
attr_reader :serial
def initialize
self.class.built += 1
@serial = self.class.built
end
end
a = Robot.new
b = Robot.new
puts "#{a.serial} #{b.serial} #{Robot.built}"출력:
1 2 2Ruby에는 클래스 변수도 있으며, @@name과 같이 작성합니다. 클래스 변수는 클래스와 모든 인스턴스가 공유하므로 인스턴스 메서드에서 직접 읽을 수 있습니다:
class Player
@@count = 0
def initialize
@@count += 1
end
def self.count
@@count
end
def others
@@count - 1
end
end
Player.new
last = Player.new
puts Player.count
puts last.others출력:
2
1클래스 변수는 모든 하위 클래스(다른 클래스를 기반으로 만들어진 클래스, 5장)와도 공유되므로, 이를 할당하는 하위 클래스는 부모 클래스의 값도 변경합니다. 클래스 인스턴스 변수는 클래스마다 별도로 유지되기 때문에 대부분의 Ruby 코드에서는 클래스 인스턴스 변수를 선호합니다:
class Base
@@kind = "base"
@label = "base"
class << self
attr_reader :label
end
def self.kind
@@kind
end
end
class Child < Base
@@kind = "child"
@label = "child"
end
puts Base.kind
puts Base.label
puts Child.label출력:
child
base
child챌린지
쉬움Ticket 클래스를 완성하세요. 새 티켓은 클래스 인스턴스 변수에 저장된 카운터에서 시작하여 1부터 다음 번호를 부여받습니다. Ticket.issued는 마지막 재설정 이후 발급된 티켓 수를 반환하고, Ticket.reset은 카운터를 0으로 되돌립니다. to_s는 #3 Concert를 반환합니다.
제공된 코드는 줄을 읽습니다. reset은 카운터를 재설정하고, 그 외의 줄은 이벤트 이름으로 처리하여 티켓을 생성하고 출력합니다. 마지막에는 issued: 2를 출력합니다.
코드는 ticket.rb에 작성하세요. main.rb에는 제공된 입력/출력 코드가 들어 있으며 수정할 수 없습니다.
직접 해보기
require_relative 'ticket'
# 제공된 입력/출력 코드: 그대로 유지하세요
input = []
while (line = gets)
input << line.chomp
end
input.each do |line|
if line == "reset"
Ticket.reset
else
puts Ticket.new(line)
end
end
puts "issued: #{Ticket.issued}"
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Ruby 컴파일러