像 put 的线路输出一样聊天

Chat like over line output of puts

我正在寻找一种在命令行上方编写代码的方法。 就像在聊天中一样,您输入的内容会显示在输入行上方。

例如:

def output(arg1, arg2)
puts arg1 + ":" + arg2
end


puts "-" *30
print "What do you want to say? > "
written_line = gets.chomp
output(username, written_line)

如果我输入"My Name is Tim",我想显示的是:

Tim: My Name is Tim
---------------------------------
What do you want to say? > _

请问有没有什么idea可以这样实现的? 谢谢

也许您正在寻找这样的东西?

def clear_line
    print "\e[2K" # Clear entire line
end

def move_up(n)
    print "\e[#{n}F" # Move to the beginning of n lines up
end

def positioning_to_output
    move_up(2)
    clear_line
end

def output(arg1, arg2)
    positioning_to_output
    puts arg1 + " :" + arg2
    clear_line
    puts "-" *30
end

username = "Jim Kirk"

4.times do
    print "What do you want to say? > "
    written_line = gets.chomp
    output(username, written_line)
end

在 macOS 上测试,多亏了发现的转义序列 here