2024-04-18 09:00:04

p vs放入Ruby

在Ruby中p和puts有区别吗?


当前回答

这可能说明了一个关键的区别,即p返回传递给它的值,而as puts返回nil。

def foo_puts
  arr = ['foo', 'bar']
  puts arr
end

def foo_p
  arr = ['foo', 'bar']
  p arr
end

a = foo_puts
=>nil
a
=>nil

b = foo_p
=>['foo', 'bar']
b
['foo', 'bar']

基准数据显示看跌期权速度较慢

require 'benchmark'
str = [*'a'..'z']
str = str*100
res = Benchmark.bm do |x|
  x.report(:a) { 10.times {p str} }
  x.report(:b) { 10.times {puts str} }
end
puts "#{"\n"*10}"
puts res

0.010000   0.000000   0.010000 (  0.047310)
0.140000   0.090000   0.230000 (  0.318393)

其他回答

foo和foo。inspect是一样的

pfoo输出foo。Inspect后面跟着换行符,即输出Inspect的值而不是to_s,这更适合调试(因为你可以区分1、"1"和"2\b1"之间的区别,如果没有Inspect就不能打印)。

这可能说明了一个关键的区别,即p返回传递给它的值,而as puts返回nil。

def foo_puts
  arr = ['foo', 'bar']
  puts arr
end

def foo_p
  arr = ['foo', 'bar']
  p arr
end

a = foo_puts
=>nil
a
=>nil

b = foo_p
=>['foo', 'bar']
b
['foo', 'bar']

基准数据显示看跌期权速度较慢

require 'benchmark'
str = [*'a'..'z']
str = str*100
res = Benchmark.bm do |x|
  x.report(:a) { 10.times {p str} }
  x.report(:b) { 10.times {puts str} }
end
puts "#{"\n"*10}"
puts res

0.010000   0.000000   0.010000 (  0.047310)
0.140000   0.090000   0.230000 (  0.318393)

同样重要的是要注意,put“react”到一个定义了to_s的类,而p没有。例如:

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 "Hello World"  
puts "Hello World".inspect

(inspect提供了一个比to_s方法更直观的对象视图)