2014-01-30 51 views
0

刪除反斜槓我有這樣如何從包含數組的字符串紅寶石

a="[\"6000208900\",\"600020890225\",\"600900231930\"]" 
#expected result [6000208900,600020890225,600900231930] 

字符串我試圖從字符串中刪除反斜槓。

a.gsub!(/^\"|\"?$/, '') 
+0

好了,所以我如何刪除這個雙引號? – Prem

+0

'a.gsub(/「/,'')' – vidaica

回答

4

Inside the double quoted string(""),另一雙引號必須由\進行轉義。你不能刪除它。

使用puts,你可以看到它不存在。

a = "[\"6000208902912790\"]" 
puts a # => ["6000208902912790"] 

或者使用JSON

irb(main):001:0> require 'json' 
=> true 
irb(main):002:0> a = "[\"6000208902912790\"]" 
=> "[\"6000208902912790\"]" 
irb(main):003:0> b = JSON.parse a 
=> ["6000208902912790"] 
irb(main):004:0> b 
=> ["6000208902912790"] 
irb(main):005:0> b.to_s 
=> "[\"6000208902912790\"]" 

更新(根據OP的最後一次編輯)

irb(main):002:0> a = "[\"6000208900\",\"600020890225\",\"600900231930\"]" 
=> "[\"6000208900\",\"600020890225\",\"600900231930\"]" 
irb(main):006:0> a.scan(/\d+/).map(&:to_i) 
=> [6000208900, 600020890225, 600900231930] 
irb(main):007:0> 
0

試試這個:

=> a = "[\"6000208902912790\"]" 
=> a.chars.select{ |x| x =~ %r|\d| }.join 
=> "6000208902912790" 
=> [a.chars.select { |x| x =~ %r|\d| }.join] 
=> ["6000208902912790"] # <= array with string 
=> [a.chars.select { |x| x =~ %r|\d| }.join].to_s 
=> "[\"6000208902912790\"]" # <= come back :) 
1

共de a.gsub!(/^\"|\"?$/, '')不能刪除雙引號字符,因爲它們不在字符串的開始和結尾處。爲了得到你想要嘗試這個東西:

a.gsub(/((?<=^\[)")|("(?=\]$))/, '') 
0
a="["6000208902912790"]" will return `unexpected tINTEGER`error; 

所以a="[\"6000208902912790\"]"用於與\字符雙引號。

作爲解決方案,您應該嘗試刪除能夠解決問題的雙引號。

做這個

a.gsub!(/"/, '')