如何在Ruby中清空终端?

57

我想知道如何在Ruby中实现类似于C语言中 system("clear") 的操作。 我写了一段程序,类似于

puts "amit"
system("clear")

我想在执行该命令后清除控制台,但它并没有起作用。


1
你在哪个操作系统上运行Ruby? - Zabba
SCiTE不是编译器,它只是一个文本编辑器。 - R. Martinho Fernandes
15个回答

70

如果你想要相对便携的东西,你可以尝试:

system "clear" || system "cls"

它将尝试清除clearcls命令。


4
иҜ·дҪҝз”Ё||д»ЈжӣҝorпјҲеҸӮи§ҒжӯӨеӨ„пјүгҖӮзӣёеә”зҡ„е‘Ҫд»Өеә”иҜҘжҳҜsystem("cls") || system("clear")гҖӮ - Eric Duminil
2
对于像我这样的“复制/粘贴”者,可能会出现以下错误:syntax error, unexpected string literal, expecting 'do' or '{' or '('system("clear") || system("cls") 可以解决这个问题。 - Jay Killeen

29

在你的 Ruby 文件中尝试以下两种方法:

puts `clear`
或者
puts "\e[H\e[2J"

9
请使用第二个选项。单纯为了清屏而分叉一个进程,这个想法让我感到头痛。欲了解更多信息,请查看此处:http://www.termsys.demon.co.uk/vtansi.htm 此外,可以使用ncurses进行更强大的控制。但是现在几乎不可能找到非ansi终端。 - Michael Chaney

18

编辑:(重新阅读您的问题后,我意识到这不是您所想要的。我以为您在提到IRB。 我会将其保留在此处,不删除,因为我觉得它可能是非常有用的信息)


最终取决于您使用的系统。

ctrl+l (<- 这是小写 L)将清除终端窗口(在Mac上是 cmd+K)。

在常规终端、Python 解释器或 MySQL 中等也同样适用。

还有很多其他快捷键可以让您熟悉和使用。我在快速搜索后找到了这个

CTRL-l - Clears the screen and places the command prompt at the top of the page.
CTRL-r - Starts a search against the command history. Start by typing in what you want to search by then press CTRL-r to see the matches.
CTRL-c - Kills the current running foreground program.
CTRL-z - Stop/sleep the current running foreground program.
CTRL-s - Stops the output to the screen.
CTRL-q - Allows output to the screen.
CTRL-a - Moves the cursor the start of the line
CTRL-e - Moves the cursor to the end of the line
CTRL-f - Moves the cursor 1 character forward
CTRL-b - Moves the cursor 1 character backward

那个列表上没有提到的是

Alt-F moves the curosor one word forward
Alt- B moves the cursor one word back

17

这是一种跨平台的做法:

Gem.win_platform? ? (system "cls") : (system "clear")

10
一个轻微的变化可以解决问题:
puts "Here's a very long string"
sleep 1
system ("cls")

马克。


6
这应该适用于Windows和OSX / Linux终端。
def method_name
   puts "amit"
   if RUBY_PLATFORM =~ /win32|win64|\.NET|windows|cygwin|mingw32/i
      system('cls')
    else
      system('clear')
   end
end
method_name

6

清屏 (Ruby 2.7+)

从 Ruby 2.7 开始,有一种内置的跨平台方式可以清除终端输出

require 'io/console'

$stdout.clear_screen # or STDOUT.clear_screen

这里查看$stdoutSTDOUT之间的区别。


4

对于Windows用户:

只需在irb窗口中输入以下函数即可:

定义此函数:

def cls
  system('cls')
end

在定义后,需要时调用此函数。


这是大多数操作系统的绝佳答案,但遗憾的是它在UNIX等系统上不起作用 :( - user17585064

4

您可以使用以下内容创建一个名为check.rb的Ruby文件:

puts "amit"
#system "clear"

并从控制台运行它 [Salil@localhost Desktop]$ check.rb

输出

[Salil@localhost Desktop]$ ruby check.rb
amit
[Salil@localhost Desktop]$ 

现在修改 check.rb 并从控制台运行它

puts "amit"
system "clear"

o/p

[Salil@localhost Desktop]$ 

3
如果您使用的是MAC OS,则请使用以下方法:
system('clear')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接