在Ruby中打印最后一行

Wor*_*man 1 ruby syntax global-variables

有没有办法让最后一个字符串的输出发送到输出?例如:

 puts "Hello"
 puts _+" World"
Run Code Online (Sandbox Code Playgroud)

会回来

 Hello
 Hello World
Run Code Online (Sandbox Code Playgroud)

我正在进行的任务涉及尽可能减少代码.以上示例不是赋值,但如果存在这样的变量,它肯定会有所帮助.

谢谢

**编辑**

@gnibbler最接近我正在寻找的答案.这与间距无关.我需要在前一行重用数据输出,而不是附加到它.另一个例子是:

 puts "foobar"   // foobar
 puts _.reverse  // raboof
Run Code Online (Sandbox Code Playgroud)

Ram*_*Vel 6

是的,它可能.你需要覆盖Kernel :: puts方法喜欢这个

module Kernel
   alias_method :old_puts, :puts
   def puts arg
       old_puts arg
       $_=arg  # $_ is a global variable, holds the last printed item
   end
end
Run Code Online (Sandbox Code Playgroud)

并使用它

>> puts "sample"
=> "sample"
>> _
=> "sample"
>> _.reverse
=> "elpmas"
Run Code Online (Sandbox Code Playgroud)

_将始终保留最后打印的值

它的意思是

>> puts "hello" 
=> "hello"
>> puts _ + " word"
=> "hello word"
>> _
=> "hello word"
Run Code Online (Sandbox Code Playgroud)