Home > Back-end >  Removing double quotes from the beging and end of an array in Ruby
Removing double quotes from the beging and end of an array in Ruby

Time:06-06

I have an array stored in a file, when I read this file to variable in Ruby it returns double quotes at the beginning and end of the array. I use Ruby 2.7.0

irb
irb(main):065:0> ports = IO.read('/ports_values')
irb(main):066:0> ports
=> "['127.0.0.1:6601:6601', '127.0.0.1:8000:8000', '127.0.0.1:7200:7200', '127.0.0.1:9201:9201', '5606:5606', '6304:6504', '6305:6505']"

But what I need this:

irb(main):066:0> ports
    => ['127.0.0.1:6601:6601', '127.0.0.1:8000:8000', '127.0.0.1:7200:7200', '127.0.0.1:9201:9201', '5606:5606', '6304:6504', '6305:6505']

without double quotes and I tried this ,but it did not work

irb(main):067:0> ports.gsub /"/, ' '
=> "['127.0.0.1:6601:6601', '127.0.0.1:8000:8000', '127.0.0.1:7200:7200', '127.0.0.1:9201:9201', '5606:5606', '6304:6504', '6305:6505']"

CodePudding user response:

a = "['127.0.0.1:6601:6601', '127.0.0.1:8000:8000', '127.0.0.1:7200:7200', '127.0.0.1:9201:9201', '5606:5606', '6304:6504', '6305:6505']"
a.slice(1..-2).split(",").map{ |b| b.strip.gsub("'","")}

o/p: ["127.0.0.1:6601:6601", "127.0.0.1:8000:8000", "127.0.0.1:7200:7200", "127.0.0.1:9201:9201", "5606:5606", "6304:6504", "6305:6505"]

  • Related