【问题标题】:Ruby - How to get rid of escape character and "\n" while converting string to hash value?Ruby - 如何在将字符串转换为哈希值时摆脱转义字符和“\ n”?
【发布时间】:2017-08-14 10:02:00
【问题描述】:

在 Ruby 中,我正在尝试将字符串转换为哈希值。它在字符串中显示为转义字符和“\n”。

例如:

hashex = { keyex: 'example "test" line 1
  line 2 "test2"'}
puts hashex

将结果打印为

{:keyex=>"example \"test\" line 1\n  line 2 \"test2\""}

我需要得到结果

{ keyex: 'example "test" line 1
      line 2 "test2"'}

保留换行符(不是'\n')和“”。请帮忙。

【问题讨论】:

    标签: ruby string


    【解决方案1】:

    注意

    {:keyex=>"example \"test\" line 1\n  line 2 \"test2\""}
    

    只是 Ruby 表示哈希的方式。它与以下对象 100% 相同:

    { keyex: 'example "test" line 1
      line 2 "test2"'}
    

    即使看起来不同。

    代码

    您可以将inspect 中的"\\n" 替换为换行符,将\" 替换为",将" 替换为'

    hashex = { keyex: 'example "test" line 1
         line 2 "test2"'}
    
    puts hashex.inspect.gsub("\\n", "\n").gsub('"', "'").gsub("\\'",'"')
    # {:keyex=>'example "test" line 1
    #      line 2 "test2"'}
    

    【讨论】:

    • 没有办法摆脱那个'\'? :(
    猜你喜欢
    • 2014-09-24
    • 2010-11-05
    • 1970-01-01
    • 2015-04-02
    • 2014-10-20
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    相关资源
    最近更新 更多