1

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.

3 Answers 3

4

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]
Sign up to request clarification or add additional context in comments.

Comments

2

You can use JSON.parse(response)

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

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.