0
array = []

File.open(file.txt) do |f|
  f.lines.each do |line|
    array << line.split.map(&:to_s)
  end
end

puts purgeObject

@test = {
  "strings" => array
}.to_json

puts @test

I need strings the output to be the following way. I keep getting an array of arrays i.e. [["334455"], ["ABC"]] - what's wrong?

{
   "strings" : [
      "334455",
      "ABC"
   ]
}
7
  • after your File.open { .. }, did you check the output of array ? Commented Mar 19, 2014 at 20:02
  • This is wrong array << line.split.map(&)... where is the method name in array << line.split.map(&..???) Commented Mar 19, 2014 at 20:05
  • Ah blindness... that's what it was. array << line.split.map(&:to_s). Thanks. Commented Mar 19, 2014 at 20:06
  • ok,... now check puts array , after the block.. Commented Mar 19, 2014 at 20:07
  • Arrays is good now. @test return [["334455"], ["ABC"]] Commented Mar 19, 2014 at 20:08

3 Answers 3

2

Just do change the line

array << line.split.map(&:to_s)

to

array.concat(line.split.map(&:to_s))

Example :

array = []
array << [1]
array << [2]
array # => [[1], [2]]
array = []
array.concat([11])
array.concat([12])
array # => [11, 12]

Actually Array#map outputs as array of some items. Thus line.split.map(&:to_s) was also giving like [item1,item2,...]. Now if you do array << line.split.map(&:to_s), then that [item1,item2,...] getting inserted into array using #<< method. So if you want to insert only item1,item2,..., then use Array#concat.

You can use foreach method also :

array = []
File.foreach(file.txt) do |line|
    array.concat(line.split.map(&:to_s))
end

@test = {
  "strings" => array
}.to_json
Sign up to request clarification or add additional context in comments.

Comments

1

A more ruby way of doing the same thing would be:

array = File.readlines('file.txt').flat_map(&:split)

@test = {
  "strings" => array
}.to_json

1 Comment

readlines is a nice touch same functionality as mine but cleaner looking +1.
0

Or why not something like

@test = {
  "strings" => File.open("file.txt",&:read).split("\n").flat_map(&:split)
}.to_json
#=> "{\"strings\":[\"this\",\"is\",\"a\",\"test\",\"file\",\"putting\",\"strings\",\"into\",\"an\",\"array\"]}"
JSON.parse(@test)
#=> {"strings"=>["this", "is", "a", "test", "file", "putting", "strings", "into", "an", "array"]}

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.