综合编程

Get the last printed line to Ruby

微信扫一扫,分享到朋友圈

Get the last printed line to Ruby
0

Is there any way to get the output of the last string sent to output? For instance:

puts "Hello"
 puts _+" World"

Would return

Hello
 Hello World

The assignment I’m working on involves minimizing code as much as possible. The above example is not the assignment, but if such a variable exists it would certainly help.

Thanks

** EDIT
**

@gnibbler has the closest answer to what I’m looking for. This has nothing to do with spacing. I need to reuse the data output on the previous line, not append to it. Another example would be:

puts "foobar"   // foobar
 puts _.reverse  // raboof

Yeah its possible. You need to override the Kernel::puts method likes this

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

and use it like

>> puts "sample"
=> "sample"
>> _
=> "sample"
>> _.reverse
=> "elpmas"

_ will always holds the last printed value

it means

>> puts "hello"
=> "hello"
>> puts _ + " word"
=> "hello word"
>> _
=> "hello word"

阅读原文...


微信扫一扫,分享到朋友圈

Get the last printed line to Ruby
0

Hello, buddy!

What’s the difference between Acceptance and Integration tests?

上一篇

谷歌chrome浏览器更新了画中画用户界面

下一篇

评论已经被关闭。

插入图片

热门分类

往期推荐

Get the last printed line to Ruby

长按储存图像,分享给朋友