如何在Ruby中清除终端?

Mil*_*lan 41 ruby

我想知道如何在Ruby中用system("clear")C语言做什么.我写了一个类似的程序

puts "amit"
system("clear")
Run Code Online (Sandbox Code Playgroud)

我希望在执行此commnad后清除控制台,但它无法正常工作.

jbr*_*jbr 53

如果你想要一些含糊不清的东西你可以尝试:

system "clear" || system "cls"
Run Code Online (Sandbox Code Playgroud)

这将尝试两个clearcls

  • 对于像我这样的复制/粘贴者来说,这可能会抛出错误:`语法错误,意外的字符串文字,期望'do'或'{'或'('``system("clear") || system("cls")`解决这个问题。 (3认同)
  • 请使用`||`而不是`or`(请参阅[here](https://github.com/rubocop-hq/ruby-style-guide#no-and-or-or))。相应的命令将是`system(“ cls”)||。系统(“清除”)` (2认同)

San*_*vin 16

在ruby文件中尝试以下任何一个:

puts `clear`
Run Code Online (Sandbox Code Playgroud)

要么

puts "\e[H\e[2J"
Run Code Online (Sandbox Code Playgroud)

  • 请在这里使用第二个.为了清除屏幕而分叉过程的想法让我头疼.有关更多信息,请参见此处:http://www.termsys.demon.co.uk/vtansi.htm另外,请查看ncurses以获得更强大的控制权.但是这些天你找到非ansi终端的可能性几乎为零. (4认同)

小智 16

这是一种多平台的方式:

Gem.win_platform? ? (system "cls") : (system "clear")
Run Code Online (Sandbox Code Playgroud)


mat*_*hew 13

编辑:(重读你的问题我意识到这不是你所追求的.我以为你指的是IRB.我会把它留在这里而不是删除它,因为我觉得它是非常有用的信息)


最终,这取决于你所使用的系统.

ctrl+ l(< - 这是一个小写的L)将清除终端( 我相信Mac上的cmd+ K)

这也适用于常规终端,python interprator或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
Run Code Online (Sandbox Code Playgroud)

那个名单上没有提到的是那个

Alt-F moves the curosor one word forward
Alt- B moves the cursor one word back
Run Code Online (Sandbox Code Playgroud)


小智 9

略有变化:

puts "Here's a very long string"
sleep 1
system ("cls")
Run Code Online (Sandbox Code Playgroud)

标记.


Ste*_*oss 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
Run Code Online (Sandbox Code Playgroud)


Mar*_*n13 6

清除屏幕(Ruby 2.7+)

从 Ruby 2.7 开始,有一种内置的跨平台方法来清除终端输出:

require 'io/console'

$stdout.clear_screen # or STDOUT.clear_screen
Run Code Online (Sandbox Code Playgroud)

请参阅此处$stdout和之间的区别。STDOUT


Sal*_*lil 4

您可以使用以下命令创建一个 ruby​​ 文件,例如 check.rb ,如下所示

puts "amit"
#system "clear"
Run Code Online (Sandbox Code Playgroud)

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

输出/输出

[Salil@localhost Desktop]$ ruby check.rb
amit
[Salil@localhost Desktop]$ 
Run Code Online (Sandbox Code Playgroud)

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

puts "amit"
system "clear"
Run Code Online (Sandbox Code Playgroud)

输出/输出

[Salil@localhost Desktop]$ 
Run Code Online (Sandbox Code Playgroud)