存储在数据库中的数据是这样的:
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
打印出实际字符。我怎样才能做到这一点?
存储在数据库中的数据是这样的:
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
打印出实际字符。我怎样才能做到这一点?
> s = "hi\nthere"
> puts s
hi
there
> puts s.gsub(/\n/, "\\n")
hi\nthere
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\"
.
> s = "line 1\n\nline2"
=> "line 1\n\nline2"
> puts s
line 1
line2
> puts s.gsub("\n", "\\n")
line 1\n\nline2
关键是转义单个反斜杠。