0

I am returning data from an api that is an array of arrays.

puts response.body 
[["20131001", 7], ["20131002", 15], ["20131003", 5]]

I need to break this up so I can insert it into a database table. However, this is being returned as a string.

results = response.body
puts results.class
String

If I convert it to an array it will have a count of 1.

results_arr =* results
puts results_arr.class
Array
puts results_arr.count
1

What is the best way to convert this into an array so I can access the elements?

UPDATE:

I have no idea why this was marked as off-topic. I'll provide an example of this problem. After I converted response.body into an array with the =* operator (confirmed by results_arr.class) I went to parse the array with this block which got the following results.

  results_arr.each do |date|
    puts date[0]
  end

This returned:

[

I believe that the issue is that converting the String returned in response.body to an Array correctly. I want to know the right way to do it. The answer provided the solution.

1
  • why is my question off-topic? Its a Ruby programming question. I provided an example and my attempts that did not work. Answers were provided that solved my problem. I do not understand why this was voted down. Commented Dec 30, 2013 at 17:49

1 Answer 1

1

Use YAML libaray of Ruby

require 'yaml'

s = '[["20131001", 7], ["20131002", 15], ["20131003", 5]]'
YAML.load(s) # => [["20131001", 7], ["20131002", 15], ["20131003", 5]]

Or JSON#parse

require 'json'

s = '[["20131001", 7], ["20131002", 15], ["20131003", 5]]'
JSON.parse(s) # => [["20131001", 7], ["20131002", 15], ["20131003", 5]]
Sign up to request clarification or add additional context in comments.

2 Comments

I guess it was meant as a JSON, not YAML. But it's hard to tell from one example...
@ArupRakshit Thanks for providing some guidance. I have no idea why my question was voted down. I appreciate your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.