Reputation: 3025
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.
Upvotes: 0
Views: 256
Reputation: 118299
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]]
Upvotes: 1