Issue regarding store file data into an array in ruby

时间:2016-12-09 12:56:00

标签: arrays ruby file parsing

I have a text file (.txt) which contains an array and the elements of these array is in string format but these are also arrays. Just like the following:

For example, lets consider my file as:

["[1, 2016-11-18 07:38:26 +0000, \"ho\"]","[1, 2016-11-18 07:38:29 +0000, \"hose cla\"]", "[1, 2016-11-18 08:24:54 +0000, \"mo\"]"]

I need to put this file data into an array.The array will look like as follows:

array = ["[1, 2016-11-18 07:38:26 +0000, \"ho\"]","[1, 2016-11-18 07:38:29 +0000, \"hose cla\"]", "[1, 2016-11-18 08:24:54 +0000, \"mo\"]"]

Right now I am unable to put the data of the file into the array using the following code statements. I am not getting the required format.

My code is:

arr=[]
arr=File.open('input.txt').map { |line| line.split(',"') }
puts arr

Help me how to achieve this.

Thanks in advance!!!

1 个答案:

答案 0 :(得分:0)

看起来你想把它解析为JSON。这应该会给你你正在寻找的输出。

require 'json'
raw = File.open('input.txt').read
array = JSON.parse(raw)