동일성과 동등성
Coddy Ruby 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 10번째.
변수는 객체 자체가 아니라 객체에 대한 참조를 보유합니다. 변수를 다른 변수에 할당하면 참조가 복사되므로, 두 이름 모두 같은 객체를 참조하게 됩니다:
class Box
attr_accessor :count
def initialize
@count = 0
end
end
a = Box.new
b = a
b.count += 1
puts a.count출력:
1equal?은 두 참조가 동일한 객체를 가리키는지 묻고, object_id는 각 객체의 고유한 번호입니다. 직접 만든 클래스에서는 기본적으로 ==도 동일하게 동작하므로, 값이 같은 두 객체도 같지 않습니다:
class Point
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
end
a = Point.new(1, 2)
b = Point.new(1, 2)
c = a
puts a == b
puts a.equal?(b)
puts a.equal?(c)
puts a.object_id == c.object_id출력:
false
false
true
true값으로 비교하도록 ==을 정의하세요. 배열의 include?, index, delete는 ==을 사용하므로, 이제 같은 객체도 찾아냅니다. 먼저 other의 클래스를 확인하세요. 그러면 숫자나 nil과 비교할 때 오류가 발생하는 대신 false를 반환합니다:
class Point
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def ==(other)
other.is_a?(Point) && x == other.x && y == other.y
end
end
a = Point.new(1, 2)
puts a == Point.new(1, 2)
puts a == 5
puts [Point.new(0, 0), Point.new(1, 2)].include?(a)
puts a.equal?(Point.new(1, 2))출력:
true
false
true
falsedup은 인스턴스 변수의 복사본을 사용해 새 객체를 만듭니다. 복사본에 새 값을 할당해도 원본에는 영향을 주지 않지만, 내부의 배열이나 문자열은 두 객체 사이에서 여전히 공유됩니다. 참조만 복사되기 때문입니다:
class Team
attr_accessor :name, :players
def initialize(name)
@name = name
@players = []
end
end
a = Team.new("Reds")
b = a.dup
b.name = "Blues"
b.players << "Ada"
puts a.name
p a.players출력:
Reds
["Ada"]챌린지
쉬움클래스 Point를 완성하여 좌표가 같은 두 점이 ==로 같다고 판정되고, 점을 다른 어떤 것과 비교하면 false가 반환되도록 하세요. to_s는 (1, 2)를 반환합니다.
제공된 코드는 점을 x,y 형식의 줄로 읽습니다. 각 점에 대해 (1, 2) same as first: true 또는 false를 출력한 다음, include?를 사용하여 서로 다른 점의 목록을 유지하고 마지막으로 distinct: 3과 첫 번째 점이 텍스트 "1,2"와 같은지 여부를 출력합니다.
코드는 point.rb에 작성합니다. main.rb에는 제공된 입력/출력 코드가 들어 있으며 편집할 수 없습니다.
직접 해보기
require_relative 'point'
# 제공된 입력/출력 코드: 그대로 유지하세요
input = []
while (line = gets)
input << line.chomp
end
points = input.map { |line| Point.new(*line.split(",").map(&:to_i)) }
points.each { |pt| puts "#{pt} same as first: #{pt == points[0]}" }
distinct = []
points.each { |pt| distinct << pt unless distinct.include?(pt) }
puts "distinct: #{distinct.size}"
puts "equals text: #{points[0] == input[0]}"
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Ruby 컴파일러