使用`puts`

时间:2015-11-18 06:19:21

标签: ruby puts

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

对我来说最有意义的是使用最后一种方法,但我只是好奇我是否应该采用这种方式来处理多行输出。

2 个答案:

答案 0 :(得分:4)

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

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的取消,因此该选项将变得更有用。

我认为使用你的第二个或第四个选项毫无意义。第三种可能会被使用,但它看起来很难看。

答案 1 :(得分:1)

TL; DR偏好和可读性

我已经搜索了以下红宝石风格指南:

Ruby Style Guide

bbatsov's Ruby Style Guide

他们都没有提到任何特定或首选的打印多个看跌期权的方法。

我认为它既有情境也有优惠。什么在这种情况下更具可读性?如果您将几个long put语句简单地作为字符串,则将它们拆分为多行的单独的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

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