PMPV

inspect와 to_s는 뭐가 다른걸까? 본문

Ruby on Rails/ruby koan

inspect와 to_s는 뭐가 다른걸까?

playinys 2018. 1. 27. 00:18
반응형

inspect와 to_s은 무엇이 다를까?

p, puts, print는 어떤 차이가 있을까?


ruby koan을 살펴보던 중, inspect라는 메서드를 활용하는 것을 보았다.

처음 보는 메서드라 검색을 해봤는데 도통 무슨 소리인지 모르겠어서 포스팅으로 정리.



역시나 정리가 잘 된 블로그는 따로 있었다.


https://rubyinrails.com/2014/11/01/difference-between-to_s-and-inspect-in-ruby/

http://descartez.github.io/blog/lessons/intro/ruby/2015/08/21/p-vs-puts.html

1.

루비에서 inspect와 to_s은 파이썬에서의 __repr__와 __str__의 차이와 같다고 한다.

문자열을 출력해 주는 것은 비슷하지만 미묘한 차이가 있다. 하지만 이 부분에 대한 문서를 거의 찾지 못했기 때문에, 혹은 찾아도 이해를 하지 못했기 때문에 이 부분을 정리하기 위한 포스팅을 시작함.


스택오버플로우에 관련된 질문이 있다. 여기를 시작점으로 삼아 구글링 시작!


Why do this Ruby object both a to_s and inspect methods that appear to do the same thing?

The p method calls inspect and puts/print calls to_s for representing the object.

  • Then, why does Ruby have two functions do the same thing? What is the difference between to_s and inspect?
  • And what's the difference between putsprint, and p?

요것이 질문. to_s과 inspect가 같은 결과를 출력해주는 것으로 보이고, 이게 뭐가 다른지 모르겠다는 질문이다.
또 부가적으로 puts와 print, p의 차이를 물어보고 있다.

답변을 보겠슴


inspect is used more for debugging and to_s for end-user or display purposes.

For example, [1,2,3].to_s and [1,2,3].inspect produce different output.

inspect는 최종 사용자 또는 표시 목적으로 디버깅 및 to_s에 많이 사용됩니다. 예를 들어 [1,2,3] .to_s 및 [1,2,3] .inspect는 서로 다른 출력을 생성합니다.


최종 사용자 또는 표시 목적,, 무슨 소리인지 모르겠다. 다음 답변으로 넘어가보겠슴

inspect is a method that, by default, tells you the class name, the instance's object_id, and lists off the instance's instance variables.

print and puts are used, as you already know, to put the value of the object's to_s method to STDOUT. As indicated by Ruby's documentation, Object#to_s returns a string representing the object -- used for end-user readability.

print and puts are identical to each other except for puts automatically appends a newline, while print does not.

inspect는 기본적으로 클래스 이름, 인스턴스의 object id를 알려주고 인스턴스의 변수를 나열해주는 메서드입니다.

print와 puts는 객체의 to_s 메서드의 값을 STDOUT로 두는 데에 사용됩니다. to_s은 객체를 나타내는 문자열을 반환합니다. 이는 최종 사용자의 가독성을 위해 사용됩니다. 

print와 puts는 newline을 제외하면 서로 동일합니다.


여전히 모르겠다.

inspect는 클래스의 이름과 인스턴스의 정보를 넘겨준다고 하는데, 이게 무슨 뜻인지 잘 모르겠다. 답변을 계속 보자.


To compare with Python, to_s is like __str__ and inspect is like __repr__to_s gives you a string, whereas inspect gives you the string representation of the object. You can use the latter to construct an object if you wish.


 to_s는 __str__과 같고 inspect는 __repr__과 같습니다. to_s는 문자열을 제공하고 inspect는 객체의 문자열 표현을 제공합니다.


문자열 제공과 객체의 문자열 표현이 무슨 차이일까?


여러가지로 검색하던 중에 많은 설명에서 p, puts, print를 언급하고 있던 것을 발견했다.

이 세가지의 차이가 실마리가 될 수 있을 것 같아서 이 쪽으로 검색을 변경했다.


이 세 가지 메서드는 커널 환경에서의 출력 기능을 수행하는 메서드이다. print와 puts는 마지막 개행을 제외하면 유의미한 차이는 없다.

p는 inspect를 수행하고 개행 문자를 출력한다. p문은 객체의 데이터 유형에 관한 정보를 리턴한다.

puts와 print는 객체에 to_s 메서드를 수행하고 문자를 출력한다. nil을 리턴한다.


p는 inspect, puts는 to_s이다. 이 두 케이스의 차이점을 확인해보자.



  2.3.3 :001 > nil.to_s

   => "" 

  2.3.3 :002 > nil.inspect

   => "nil" 




  2.3.3 :001 > hash = Hash.new

   => {} 

  2.3.3 :002 > hash = {name: "pak", age: 27, univ: "sku"}

   => {:name=>"pak", :age=>27, :univ=>"sku"} 

  2.3.3 :003 > hash

   => {:name=>"pak", :age=>27, :univ=>"sku"} 

  2.3.3 :004 > puts hash

  {:name=>"pak", :age=>27, :univ=>"sku"}

   => nil 

  2.3.3 :005 > p hash

  {:name=>"pak", :age=>27, :univ=>"sku"}

   => {:name=>"pak", :age=>27, :univ=>"sku"} 

  2.3.3 :006 > puts hash[:name]

  pak

   => nil 

  2.3.3 :007 > p hash[:name]

  "pak"

   => "pak" 




  2.3.3 :001 > num = 1

   => 1 

  2.3.3 :002 > num_string = "1"

   => "1" 

  2.3.3 :003 > p num

  1

   => 1 

  2.3.3 :004 > p num_string

  "1"

   => "1" 

  2.3.3 :005 > puts num

  1

   => nil 

  2.3.3 :006 > puts num_string

  1

   => nil 



puts의 경우, 객체를 문자열 형태로 반환하여 출력해주고, 리턴 값은 nil이다.

p의 경우는 문자열 형태의 출력뿐만 아니라, 객체의 데이터 유형과 인스턴스 변수까지 함께 반환해준다.

터미널에서 배열이나 해시의 형태를 테스트 할 때, 이 차이가 명확하게 드러나지 않을 수 있다.


객체가 오버라이딩 되지 않았고 인스턴스 변수가 없는 경우, 둘의 차이는 없다.


단순 문자열을 출력한다면 to_s을 이용하는 편이 낫다. 하지만 디버깅을 위해서 우리는 더 많은 정보가 있을 수록 좋을 것이다.

그럴 땐 inspect를 이용해 객체를 검사하는 편이 낫다.


class Item
def initialize(item_name, qty)
@item_name = item_name
@qty = qty
end

# override 'to_s' here
end

item = Item.new("a",1)

puts item
p item

#<Item:0x007fd1c613b8a8>                                #인스턴스 변수는 없이 item의 참조값만 출력                            #<Item:0x007fd1c613b8a8 @item_name="a", @qty=1>         #인스턴스 변수를 함께 출력




뭔가 정리가 잘 안된것 같지만 여기서 마무리


반응형

'Ruby on Rails > ruby koan' 카테고리의 다른 글

ruby koan 가이드 v.2  (0) 2018.02.06
assert equal은 어디에서 나온 놈일까?  (0) 2018.01.25
루비에서 object id는 왜 홀수일까?  (0) 2018.01.22
Comments