为什么内核#p在标准输出上复制我的文本?

Poo*_*oya -1 ruby io

看看这段代码:

def hello
   p "Hey!"
end
p hello
Run Code Online (Sandbox Code Playgroud)

输出将是:

"Hey!"
"Hey!"
=> "Hey!"
Run Code Online (Sandbox Code Playgroud)

所以这是我的结论:put本身返回将在Ruby代码中输出的文本,否则它不会打印"嘿!" 再次.打印字符串时发生了什么?如果puts不直接将它发送到标准输出,谁负责它以及如何?

Tod*_*obs 5

所有方法都返回一个值

在Ruby中,几乎所有东西都返回一个值,即使该值为零.但是,在您的情况下,问题是内核#p内核#put在它们返回的值有所不同.

def hello
   # Print string literal, then return
   # the printed object.
   p "Hey!"
end

# Print the return value of main#hello.
p hello
Run Code Online (Sandbox Code Playgroud)

结果,字符串在方法内部被打印一次,然后方法的返回值被传递给内核#p并再次打印.这是设计的.

使用Kernel#puts避免重复输出

def hello
   # Print string; return nil.
   puts "Hey!"
end

# Calls main#hello, but prints nil (blank line).
puts hello
Run Code Online (Sandbox Code Playgroud)

这将导致在方法内打印字符串文字,然后打印一个空白行,因为方法的返回值为nil.

Hey!

=> nil
Run Code Online (Sandbox Code Playgroud)

正确的方式

如果要避免空白行,请避免多次发送到标准输出.例如:

def hello
  'Hey!'
end

p hello
Run Code Online (Sandbox Code Playgroud)