而不是使用大量的“put”,如何使用“one puts”在ruby中编写许多字符串

时间:2016-08-13 23:58:02

标签: ruby-on-rails ruby pretty-print

我试图在Ruby中使我的代码更漂亮。我已经使用了很多这样的“看跌期权”;

  puts "something 1"
  puts "something 2"
  puts "something 3"

我尝试使用一个“puts”以相同的格式编写所有这些,我正在尝试这样的东西,但它不起作用;

puts << "something 1" << "something 2" << "something 3"

你能不能用更好的方式建议我使用大量的“看跌期权”来写这些东西?

3 个答案:

答案 0 :(得分:1)

somethings = ['something 1', 'something 2', 'something 3']
puts somethings.join("\n")

答案 1 :(得分:0)

使用print打印出同一行中的所有变量,或使用换行符打印puts

x = "something"
y = 1
z = true

print x,y,z
print "\n"
puts x,y,z

输出:

something1true
something
1
true

如果它是全部字符串,您可以随时使用<<+连接它们,如下所示:

puts "something1" + "something2" + "something3"
puts "something1" << "something2" << "something3"

答案 2 :(得分:0)

# if you do create an array variable, then here are two more options
stuff = ["something1", "something2", "something3"]
stuff.each { |i| puts i }   # on  seperate lines
puts ("%s " * stuff.size) % stuff # all on one line


# you can still make use of arrays even without a seperate variable
puts ["something1", "something2", "something3"]  # on seperate lines
puts ["something1", "something2", "something3"].join(' ')  # on one line
puts "%s %s %s " % ["something1", "something2", "something3"]  # same as the second option above really

# then there is just concat as mentioned above, but it seems ugly if you want to include spaces
puts "something1" + " " + "something2" + " " + "something3"  # ugly imho