6

我有一个这样的字符串string1

Hello World, join my game:

我想让 string1 变成:

Hello World, join my game:

http://game.com/url

如何使用 ruby​​ 附加回车,然后附加来自另一个变量的链接?

谢谢

4

5 回答 5

20

这实际上取决于您要输出的内容。

$标准输出:

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
于 2012-04-05T18:03:25.157 回答
6

假设你有这些字符串:

string1 = 'foo'
string2 = 'bar'

这是将它们与中间换行符组合的三种方法:

字符串插值:

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

'+' 运算符:

string1 + "\n" + string2

数组和.join

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

或者

[string1, string2].join("\n")
于 2012-04-05T18:00:23.830 回答
2

据我所知,没有新的线路常数。使用转义序列 '\n'。像:

puts "1. Hello\n2. World"

参考:http ://en.wikibooks.org/wiki/Ruby_Programming/Strings

于 2012-04-05T17:56:15.537 回答
2

如果您使用 puts 语句,则在新行上打印的简单方法如下:

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 中运行代码。

于 2014-02-05T15:25:02.010 回答
1

以数组形式输出。

如果您要多次附加到同一个字符串变量,并且您想稍后在新行中输出这些附加字符串中的每一个,您可能需要考虑使用数组来存储每个字符串,然后在显示/输出它们。

output = []

output << "Hello World, join my game:"

output << "http://game.com/url"

output << "Thank You!"

现在,如果您在终端或其他地方,您可以puts在输出数组上使用:

puts output
#=> Hello World, join my game:
#=> http://game.com/url
#=> Thank You!

如果你想在 HTML 中显示它,你可能需要使用以下join()方法:

output.join('<br>')
#=> "Hello World, join my game:<br>http://game.com/url<br>Thank You!"

你可以在方法中使用任何你喜欢的东西join(),所以如果你想在每个字符串之间有两个换行符,你可以这样做:

puts output.join("\n\n")
#=> Hello World, join my game:

#=> http://game.com/url

#=> Thank You!
于 2018-03-15T04:18:25.220 回答