Search code examples
ruby-on-railsrubyloopsfile-iotextinput

How to insert response string into file as separate lines with each word?


Is there a way to put keywords of strings you get into a text file, but as each word gets entered they each have their own line. for example : "dog cat pig" would be:

"dog"
"cat"
"pig"
... and so on 

^^^ I'm trying to make the text file look like this, instead of how it does below

I'm searching through tag list for and I would like the results to get put in a text file to have each word have its own line. Is this doable?

Here's my code:

getusers = client.get('/tracks', :genre => 'pop', :limit => 200 )

file = File.new("tag_list.txt","a")
array1 = []

getusers.each { |t| 
  puts t.tag_list 
  file.puts "#{t.tag_list}"
}

My response:

enter image description here

^^^ when inserted into the text file it will looked exactly how its written above. any help/idea would be much appreciated :)


Solution

  • You can have a try.

     getusers.each { |t| 
          puts t.tag_list
          if not t.tag_list.blank?
             t.tag_list.split(" ").each do |word|
               file.puts word
             end
          end
     }