2017-08-28 57 views
-2

的字符串表示的子我有一个字符串如下,这是在JSON格式:红宝石更换JSON

test_geometry_profile = 
    '{ 
    "geometryProfile": { 

     "SPEEDSeedModel0.osm": { 
     "WWR": 0.5, 
     "Orientation": 0.0 
     }, 

     "SPEEDSeedModel1.osm": { 
     "WWR": 0.6, 
     "Orientation": 0.0 
     } 
    } 
    }' 

我想与'TestOSM_radiantDOAS.osm'替换子SPEEDSeedModel1.osm在此字符串。

我使用的代码:

test_geometry_profile.sub("SPEEDSeedModel1.osm", 'TestOSM_radiantDOAS.osm') 

然而,这无法工作。有什么我在这里失踪?

回答

1

它正在工作,但sub返回字符串的一个副本并进行了替换。您可以通过运行来看到这一点:

test_geometry_profile = 
    '{ 
    "geometryProfile": { 

     "SPEEDSeedModel0.osm": { 
     "WWR": 0.5, 
     "Orientation": 0.0 
     }, 

     "SPEEDSeedModel1.osm": { 
     "WWR": 0.6, 
     "Orientation": 0.0 
     } 
    } 
    }' 

puts test_geometry_profile 
puts test_geometry_profile.sub("SPEEDSeedModel1.osm", 'TestOSM_radiantDOAS.osm') 
puts test_geometry_profile 

第二个值输出将会做出更改,第三个是原始字符串。你想要的是sub!,从而改变了串到位:

puts test_geometry_profile 
puts test_geometry_profile.sub!("SPEEDSeedModel1.osm", 'TestOSM_radiantDOAS.osm') 
puts test_geometry_profile 

现在,第二和第三值具有新的字符串。