Ruby中的符号替换

swi*_*ure 0 ruby

我有一个由其他人生成的地图,其数据结构如下:

x = {"city": "London", "country": "England", "region": "Europe"}
Run Code Online (Sandbox Code Playgroud)

我想在Ruby中操纵数据.因此,为了能够让Ruby了解它是一张地图,我需要将所有内容替换":""=>".有没有一种快速的方法可以在一行中实现这一目标?

Sub*_*Rao 13

你需要安装这个宝石json

sudo gem install json

    require 'json'
    JSON.parse('{"city": "London", "country": "England", "region": "Europe"}')
Run Code Online (Sandbox Code Playgroud)

  • 它还避免了将外部输入作为代码执行. (2认同)

col*_*rco 5

my_text = 'x = {"city": "London", "country": "England", "region": "Europe"}'

# Replace : with =>
ruby_code = t.gsub(':', '=>')

# Evaluate the string as ruby code
eval ruby_code

# Now you can access the hash

x['city'] # => "London"
Run Code Online (Sandbox Code Playgroud)

  • 只有当你确定钥匙或值中永远不会有冒号时才这样做!如果有任何可能性,请使用Subba Rao建议的JSON方法. (3认同)
  • 这是非常不安全和脆弱的.使用"eval"几乎总是错误的.Subba Rao的答案要好得多. (2认同)