2016-08-13 44 views

回答

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

有沒有辦法不創建數組?只是尋找一個語法,寫一個投入和打印兩個字符串只是一個puts.There幾個放在幾個不同的地方,我不想爲他們每個人創建一個數組。 –

+0

你想爲整個結果使用一個換行符,還是爲每個字符串使用不同的換行符?有很多方法可以做到這一點,例如heredocs,字符串插值和字符串連接(即「hello」+「world」) –

0

使用print打印出所有變量在同一行,或puts新行:

x = "something" 
y = 1 
z = true 

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

輸出:

something1true 
something 
1 
true 

如果它的所有字符串,你可以隨時Concat的他們使用<<+像這樣:

puts "something1" + "something2" + "something3" 
puts "something1" << "something2" << "something3" 
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 
相關問題