将控制台消息与代码分离



我正在尝试制作命令行应用程序。puts行使代码看起来杂乱无章。例如,我有一个help命令,它有几个puts

def help()
    puts "Welcome to my app"
    puts "..."
    puts "..."
    puts "..."
    puts "..."
end

如果我将puts组合为一,输出将包括尾部空间

def help()
    puts "Welcome to my app
    ...
    ..."
end
# The output in the console will be like:
# Welcome to my app
#        ...
#        ...

将消息与代码分离的最佳方法是什么?我只能考虑使用变量来存储消息,但我相信有一种更好、更整洁的方法,比如markdown或使用txt。

对于您的问题,我认为您正在STDLIB中寻找OptParser库。

它允许您构建命令行选项,以便为用户执行使用情况和命令行报告等操作。

然而,您可以在help方法中做到这一点:

def help
  <<-EOS.lines.each {|line| line.strip!}
  Welcome to my app
  ...
  ...
  EOS
end
puts help
puts "Thank you for using my app!"

这将显示为这样。

Welcome to my app           
...                         
...                         
Thank you for using my app!

更新:我将EOF分隔符更改为字符串结尾的EOS。

def help
    puts 
    "Welcome to my app"
    "..."
    "..."
    "..."
    "..."
    "..."
end

在您的特定示例中,您可以在帮助函数中执行

puts "Welcome to my app", "...n"*3

如果你有很多这样的静态消息,你可以尝试在的开头使用散列

messages = {"welcome" => "Welcome to my appn" + "...n"*3, 
           "thanks" => "Thank you for the action"}

然后你可以作为访问它们

puts messages["welcome"]

最新更新