is_a?와 ancestors
Coddy Ruby 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 25번째.
is_a?(Class)는 객체가 해당 클래스 또는 그 클래스의 모든 하위 클래스의 인스턴스인지 확인합니다. kind_of?는 동일한 메서드의 또 다른 이름입니다.
class Animal
end
class Dog < Animal
end
rex = Dog.new
puts rex.is_a?(Dog)
puts rex.is_a?(Animal)
puts rex.is_a?(Object)
puts rex.kind_of?(String)출력:
true
true
true
falseinstance_of?는 더 엄격합니다. 객체 자체의 클래스일 때만 true입니다. obj.class는 해당 클래스를 반환합니다:
class Animal
end
class Dog < Animal
end
rex = Dog.new
puts rex.instance_of?(Dog)
puts rex.instance_of?(Animal)
puts rex.class출력:
true
false
Dogancestors는 Ruby가 메서드를 검색하는 클래스들을 클래스 자체부터 시작하여 나열합니다. 전체 목록에는 6장에서 다루는 Kernel과 같은 모듈도 포함되므로 take(3)은 처음 항목 3개를 보여 줍니다. 클래스를 비교할 수도 있습니다. Dog < Animal은 Dog이 Animal을 상속할 때 true입니다.
class Animal
end
class Dog < Animal
end
p Dog.ancestors.take(3)
puts Dog < Animal
puts Animal < Dog출력:
[Dog, Animal, Object]
true
false코드에서 여러 클래스의 그룹을 같은 방식으로 처리해야 할 때는 is_a?를 사용하세요. 예를 들어 어떤 하위 클래스인지와 관계없이 모든 포유류를 세는 경우입니다. instance_of?로 하나의 정확한 클래스를 요청하면 누군가 하위 클래스를 추가하는 순간 문제가 발생합니다:
mammals = animals.count { |a| a.is_a?(Mammal) } # 개, 박쥐, 고래...
exact = animals.count { |a| a.instance_of?(Mammal) } # 모든 하위 클래스를 놓침챌린지
쉬움동물 클래스를 선언하세요: Animal, Mammal < Animal, Bird < Animal, Dog < Mammal, Bat < Mammal 및 Penguin < Bird. Animal은 이름을 저장합니다. 그런 다음 functions.rb에서 도우미 describe(animal)을 완성하세요. 이 도우미는 클래스 이름을 소문자로 표시하고 is_a?를 사용해 그룹을 결정하여 Rex is a dog: mammal, Pingu is a penguin: bird를 반환합니다.
제공된 코드는 dog Rex 줄을 읽고, 객체를 생성하고, 각 객체에 대해 describe를 출력한 다음 mammals: 2, birds: 1을 출력합니다.
코드는 animal.rb, mammal.rb, bird.rb, dog.rb, bat.rb, penguin.rb 및 functions.rb에 작성하세요. main.rb에는 제공된 입력/출력 코드가 포함되어 있으며 편집할 수 없습니다.
직접 해보기
require_relative 'animal'
require_relative 'mammal'
require_relative 'bird'
require_relative 'dog'
require_relative 'bat'
require_relative 'penguin'
require_relative 'functions'
# 제공된 입력/출력 코드: 그대로 유지하세요
input = []
while (line = gets)
input << line.chomp
end
kinds = { "dog" => "Dog", "bat" => "Bat", "penguin" => "Penguin" }
animals = input.map do |line|
kind, name = line.split
Object.const_get(kinds[kind]).new(name)
end
animals.each { |a| puts describe(a) }
mammals = animals.count { |a| a.is_a?(Mammal) }
birds = animals.count { |a| a.is_a?(Bird) }
puts "mammals: #{mammals}, birds: #{birds}"
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Ruby 컴파일러