Bloomberg
Bloomberg

Reputation: 2357

how to remove backslash from a string containing an array in ruby

I have a string like this

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

I am trying to remove the backslash from the string.

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

Upvotes: 2

Views: 2549

Answers (4)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Inside the double quoted string(""), another double quotes must be escaped by \. You can't remove it.

Use puts, you can see it is not there.

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

Or use 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\"]"

update (as per the last edit of 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>

Upvotes: 6

Alok Anand
Alok Anand

Reputation: 3356

a="["6000208902912790"]" will return  `unexpected tINTEGER`error; 

so a="[\"6000208902912790\"]"is used with \ character for double quotes.

As a solution you should try to remove double quotes that will solve the problem.

Do this

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

Upvotes: 0

vidang
vidang

Reputation: 1771

The code a.gsub!(/^\"|\"?$/, '') can't remove the double quote characters because they are not at the beginning and the end of the string. To get what you want try this:

a.gsub(/((?<=^\[)")|("(?=\]$))/, '')

Upvotes: 1

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

try this:

=> 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 :)

Upvotes: 0

Related Questions