【问题标题】:Preferred style for displaying multiple lines using `puts`使用 `puts` 显示多行的首选样式
【发布时间】:2016-02-19 18:37:40
【问题描述】:

我知道有几种不同的方法可以将puts 语句组合成一个语句。但更重要的是,我正在尝试确定是否有一种普遍接受/首选的风格(我只能挖掘其他人的聪明做法,但没有关于首选风格的真正参考)。

我见过这样的事情:

puts "This", "is", "fairly", "easy"  # Each word goes on it's own line

或者也许:

puts ["This", "seems", "convoluted"].join("\n") # Each word goes on it's own line

或“丑陋”的方式:

  def ugly_puts
    puts "Not using quotes
And using no code indentation to preserve output formatting"
  end

或者简单地说:

puts "This"
puts "Seems" 
puts "Straightforward."

使用最后一种方法对我来说最有意义,但我只是好奇是否有一种常见/首选的方式来处理这样的多行输出。

【问题讨论】:

    标签: ruby puts


    【解决方案1】:

    如果要打印的行足够短,可以放在源代码的一行中,那么我会选择您的第一个选项:

    puts "This", "is", "fairly", "easy"
    

    如果它们很长,那么我会使用heredoc:

    puts <<_.unindent
      This Blah Blah ...
      Seems Blah Blah ...
      Straightforward. Blah Blah ...
    _
    

    其中unindent 是一种按照Ruby indented multiline strings 中建议的行取消缩进缩进的heredoc 的方法。请注意,在未来的 Ruby 版本中,可能会有一种更简单的方法来取消缩进 heredoc,因此此选项将变得更加有用。

    我认为使用您的第二个或第四个选项没有意义。第三个可以用,但是看起来很丑。

    【讨论】:

    • 知道unindent 似乎是一个Ruby gem,需要先安装才能使用这种样式,这可能对其他人有所帮助。
    【解决方案2】:

    TL;DR 偏好和可读性

    我浏览了以下 ruby​​ 样式指南:

    Ruby Style Guide

    bbatsov's Ruby Style Guide

    他们都没有提到打印多个 puts 语句的任何特定或首选方法。

    我认为这既是情境性的,也是优先性的。在这种情况下什么更具可读性?如果您有几个长的 puts 语句作为简单的字符串,请将它们拆分为多行的单独 puts 语句。

    puts "Something very longgggggggggggg"
    puts "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an..."
    puts  "unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing..."
    

    如果您出于某种原因将单独的语句存储在变量中,只需将它们全部放在一行上:puts this, that, thing

    为了在方法中存储 puts 语句,当您想在控制台中打印多行时可能会很方便。例如,当制作一个用户将通过终端进行交互和使用的程序时,您可能希望将某些语句存储在方法中并在用户调用时将它们打印出来(即打印出指令或打印出可用的命令)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 2015-11-11
      • 2011-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多