2017-08-28 58 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 

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