2

我知道有几种不同的方法可以将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."

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

4

2 回答 2

4

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

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

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

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

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

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

于 2015-11-18T07:23:53.110 回答
1

TL;DR 偏好和可读性

我搜索了以下 ruby​​ 样式指南:

红宝石风格指南

bbatsov 的 Ruby 风格指南

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

我认为这既是情境性的,也是优先性的。在这种情况下什么更具可读性?如果您有几个长的 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 语句,有时您想在控制台中打印几行可能会很方便。例如,当制作一个用户将通过终端进行交互和使用的程序时,您可能希望将某些语句存储在方法中并在用户调用时将它们打印出来(即打印出指令或打印出可用的命令)。

于 2015-11-18T06:47:55.190 回答