How to print raw string in ruby?

两盒软妹~` 提交于 2019-12-25 07:39:37

问题


I want to print escaped or raw version of a string. For example: given this string:

"a,
b,
c,
d"

I want to get

"a,\nb,\nc,\nd".

Is it possible?


回答1:


string = 'a,
b,
c,
d'

> p string.inspect
#=> "\"a,\\nb,\\nc,\\nd\""
# "*** expected output ***"
> p string.inspect.delete('\"')
#=> "a,\\nb,\\nc,\\nd"

Demo




回答2:


s = "a,
b,
c,
d"
s.dump
# => "\"a,\\nb,\\nc,\\nd\"" 
s.dump[1...-1]
# => "a,\\nb,\\nc,\\nd" 


来源:https://stackoverflow.com/questions/34148616/how-to-print-raw-string-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!