IT

p 대 루비를 넣습니다

lottoking 2020. 3. 31. 08:28
반응형

p 대 루비를 넣습니다


루비 p차이점이 puts있습니까?


p foo인쇄는 foo.inspect, 개행 다음은 값 출력, 즉 inspect대신에 to_s(당신이 예 사이의 차이를 말할 수 있기 때문에 디버깅에 더 적합 1, "1"그리고 "2\b1"당신이없이 인쇄 할 수 없을 때하는 inspect).


또한 정의 된 puts클래스에 "반응" 하지 않는다는 점에 유의해야합니다 . 예를 들면 다음과 같습니다.to_sp

class T
   def initialize(i)
      @i = i
   end
   def to_s
      @i.to_s
   end
end

t = T.new 42
puts t   => 42
p t      => #<T:0xb7ecc8b0 @i=42>

이것은 .inspect전화 에서 직접 따르지만 실제로는 명확하지 않습니다.


p foo 와 같다 puts foo.inspect


위의 답변 외에도 콘솔 출력에는 미묘한 차이가 있습니다. 즉, 반전 된 쉼표 / ​​따옴표가 있는지 여부는 유용합니다.

p "+++++"
>> "+++++"

puts "====="
>> =====

가까운 친척 print를 사용하여 간단한 진행률 표시 줄을 만들고 싶다면이 기능이 유용하다는 것을 알았습니다 .

array = [lots of objects to be processed]
array.size
>> 20

100 % 진행률 표시 줄이 나타납니다.

puts "*" * array.size
>> ********************

그리고 이것은 각 반복마다 증분 *을 추가합니다.

array.each do |obj|
   print "*"
   obj.some_long_executing_process
end

# This increments nicely to give the dev some indication of progress / time until completion
>> ******

에서 루비 2.4.1 문서

넣다

puts(obj, ...) → nil

주어진 객체를 ios에 씁니다. 개행 시퀀스로 끝나지 않은 개행 후에 개행씁니다 . nil을 리턴 합니다.

쓰기 위해 스트림을 열어야합니다. 배열 인수 와 함께 호출되면 각 요소 를 새 줄에 씁니다 . 문자열이나 배열이 아닌 각 주어진 객체는 to_s메소드 를 호출하여 변환됩니다 . 인수없이 호출하면 단일 줄 바꿈이 출력됩니다.

irb로 해보자

# always newline in the end 
>> puts # no arguments

=> nil # return nil and writes a newline
>> puts "sss\nsss\n" # newline in string
sss
sss
=> nil
>> puts "sss\nsss" # no newline in string
sss
sss
=> nil

# for multiple arguments and array
>> puts "a", "b"
a
b
=> nil
>> puts "a", "b", ["c", "d"]
a
b
c
d
=> nil

p(obj) → obj click to toggle source
p(obj1, obj2, ...) → [obj, ...] p() → nil
각 객체 obj.inspect에 대해 프로그램의 표준 출력에 개행을 직접 씁니다 .

irb에서

# no arguments
>> p
=> nil # return nil, writes nothing
# one arguments
>> p "sss\nsss\n" 
"sss\nsss\n"
=> "aaa\naaa\n"
# multiple arguments and array
>> p "a", "b"
"a"
"b"
=> ["a", "b"] # return a array
>> p "a", "b", ["c", "d"]
"a"
"b"
["c", "d"]
=> ["a", "b", ["c", "d"]] # return a nested array

이 2 개는 동일합니다 :

p "Hello World"  
puts "Hello World".inspect

( inspectto_s 메소드 와 비교하여 객체를보다 문자 그대로 보여줍니다 )

참고 URL : https://stackoverflow.com/questions/1255324/p-vs-puts-in-ruby

반응형