Supersonic
Supersonic

Reputation: 430

Better way to convert string to array

I have a http response from a url :

response = Net::HTTP.get(uri) 
=> "[1,2,3,4,5]"

response is a string but I would like to convert it to an array like

=> [1,2,3,4,5]

So I am doing this currently :

response = response.split('[').join.split(']').join.split(',').map{|n| n.to_i}

I feel this is not the rite way, is there any better way to do it. Thanks in advance.

Upvotes: 1

Views: 50

Answers (3)

hamdiakoguz
hamdiakoguz

Reputation: 16275

You can use a little bit of regex if you don't want to parse it as json.

"[1,2,3,4,5]".scan(/\d+/).map(&:to_i)

Upvotes: 2

fylooi
fylooi

Reputation: 3870

You can use JSON.parse(response)

http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html

Upvotes: 2

falsetru
falsetru

Reputation: 369074

For me, it looks like json string. You can use JSON#parse to parse it:

require 'json'
JSON.parse "[1,2,3,4,5]"
# => [1, 2, 3, 4, 5]

Upvotes: 4

Related Questions