我有一个由其他人生成的地图,其数据结构如下:
x = {"city": "London", "country": "England", "region": "Europe"}
我想在Ruby中操纵数据.因此,为了能够让Ruby了解它是一张地图,我需要将所有内容替换":"
为"=>"
.有没有一种快速的方法可以在一行中实现这一目标?
你需要安装这个宝石json
sudo gem install json
require 'json' JSON.parse('{"city": "London", "country": "England", "region": "Europe"}')
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"