2

存储在数据库中的数据是这样的:

This is a line

This is another line

How about this line

当我将其输出到视图时,我想将其转换为:

This is a line\n\nThis is another line\n\nHow about this line

没有新行并且\n打印出实际字符。我怎样才能做到这一点?

4

3 回答 3

7
> s = "hi\nthere"
> puts s
hi
there
> puts s.gsub(/\n/, "\\n")
hi\nthere
于 2013-01-23T17:56:09.287 回答
2

gsub如果您只想专门转换换行符,我会亲自使用。但是,如果您想普遍检查字符串的内容,请执行以下操作:

str = "This is a line\n\nThis is another line\n\nHow about this line"
puts str.inspect[1..-2]
#=> This is a line\n\nThis is another line\n\nHow about this line

String#inspect方法转义字符串中的各种“控制”字符。它还用"我在上面剥离的字符串包裹了字符串。请注意,这可能会产生不希望的结果,例如字符串My name is "Phrogz"将作为My name is \"Phrogz\".

于 2013-01-23T19:05:54.997 回答
1
> s = "line 1\n\nline2"
 => "line 1\n\nline2"  

> puts s
line 1

line2

> puts s.gsub("\n", "\\n")
line 1\n\nline2

关键是转义单个反斜杠

于 2013-01-23T17:56:05.947 回答