2012-04-05 36 views
2

我有像這樣string1的字符串:給定一個字符串,如何附加一個回車後跟另一個字符串?

Hello World, join my game: 

我想提出字符串1成爲:

Hello World, join my game: 

http://game.com/url 

我如何可以追加紅寶石回車,然後從另一個變量的鏈接?

THanks

+0

'「#{string1} \ n \ nhttp://game.com/url」' – 2012-04-05 17:54:39

+1

@Michael也許你打算有'#'而不是'%'? – 2012-04-05 17:56:48

+0

@Michael很確定這實際上是'「#{string1}」',而不是'「%{string1}」' – MrTheWalrus 2012-04-05 17:57:01

回答

12

這真的取決於你輸出什麼。

$ STDOUT:

puts "Hello\n\n#{myURL}" 

puts "Hello" 
puts 
puts myURL 

puts <<EOF 
Hello 

#{myURL} 
EOF 

如果你是一個html.erb.rhtml文檔輸出這樣的:

<%= "Hello<br /><br />#{myURL}" %> # or link_to helper 

如果你已經有一個像string1一個字符串,那麼你可以追加到它使用兩種+=<<

string1 = "Hello world, join my game:" 
myUrl = "http://example.com" 
string1 += "\n\n#{myUrl}" 

或:

string1 = "Hello world, join my game:" 
myUrl = "http://example.com" 
string +=<<EOF 

#{myUrl} 
Here's some other details 
EOF 
4

假設你有這些字符串:

string1 = 'foo' 
string2 = 'bar' 

這裏有三種方式將它們與新行之間結合:

字符串插值:

"#{string1}\n#{string2}" 

'+' 操作:

string1 + "\n" + string2 

陣列和。加入

[string1, "\n", string2].join 

OR

[string1, string2].join("\n") 
0

如果使用看跌期權語句,一個簡單的方法以新行打印如下:

puts "Hello, here is the output on line1", "followed by some output on line2" 

這將返回:

Hello, here is the output on line1 
followed by some output on line2 

如果您在終端中運行irb中的代碼。

相關問題