Menu
Coddy logo textTech

to_s와 inspect

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

puts는 객체의 to_s 메서드를 호출하여 객체를 텍스트로 변환합니다. 기본 to_s는 클래스 이름과 메모리 주소만 제공합니다. 예를 들어 #<Book:0x000055d0>처럼 표시되므로, 클래스는 자체 메서드를 정의합니다. 문자열 보간에서도 to_s를 호출합니다:

class Book
  def initialize(title, pages)
    @title = title
    @pages = pages
  end

  def to_s
    "#{@title} (#{@pages} pages)"
  end
end

book = Book.new("Dune", 412)
puts book
puts "Reading #{book}"

출력:

Dune (412 pages)
Reading Dune (412 pages)

join은 각 요소에 대해 to_s도 호출하므로, 객체 배열을 사용하면 사용자가 정의한 형식으로 출력됩니다:

class Book
  def initialize(title)
    @title = title
  end

  def to_s
    @title.upcase
  end
end

shelf = [Book.new("Dune"), Book.new("Emma")]
puts shelf.join(", ")
puts "Shelf: #{shelf.join(" / ")}"

출력:

DUNE, EMMA
Shelf: DUNE / EMMA

p는 프로그래머를 위한 것으로, 값을 모호하지 않게 보여 주는 inspect를 출력합니다. 문자열은 따옴표를 유지하고 nil은 표시됩니다. 사용자 고유의 객체에서는 기본 inspect가 인스턴스 변수를 나열합니다:

p "Dune"
puts "Dune"
p [1, "a", nil]
puts [1, "a", nil].inspect

출력:

"Dune"
Dune
[1, "a", nil]
[1, "a", nil]

디버깅을 위해 짧고 정확한 설명을 얻도록 inspect를 재정의하세요. 배열의 p와 inspect는 이를 사용하지만, puts는 계속 to_s를 사용합니다:

class Point
  def initialize(x, y)
    @x = x
    @y = y
  end

  def to_s
    "(#{@x}, #{@y})"
  end

  def inspect
    "#<Point x=#{@x} y=#{@y}>"
  end
end

pt = Point.new(1, 2)
puts pt
p pt
p [pt, Point.new(0, 5)]

출력:

(1, 2)
#<Point x=1 y=2>
[#<Point x=1 y=2>, #<Point x=0 y=5>]
challenge icon

챌린지

쉬움

Track 클래스를 완성하세요. initialize(title, artist, seconds)는 값을 저장합니다. to_s는 길이를 분 단위와 두 자리 초 단위로 표시하여 Dune by Ada (3:05)를 반환하고, inspect는 제목을 큰따옴표로 묶은 #<Track "Dune" 185s>를 반환합니다.

제공된 코드는 트랙을 title,artist,seconds 형식의 줄로 읽고, 각 트랙을 puts로 출력한 다음 전체 목록을 p로 출력합니다.

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

직접 해보기

require_relative 'track'

# 제공된 입력/출력 코드: 그대로 유지하세요
input = []
while (line = gets)
  input << line.chomp
end
tracks = input.map do |line|
  title, artist, seconds = line.split(",")
  Track.new(title, artist, seconds.to_i)
end
tracks.each { |t| puts t }
p tracks
quiz icon실력 점검

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

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

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