cmart
cmart

Reputation: 91

How do I save a string to a CSV file in Ruby?

I have written code but it will not work. The code is:

 #Parse and print the Tweet if the response code was 200
tweets = nil
if response.code == '200' then
tweets = JSON.parse(response.body)
require 'csv'
CSV.open("trial.csv", "ab") do |csv|
  csv << ["text", "created_at", "name", 'id']
  csv << ["tweets"]
  end
end

How would I change this code to save the tweets to a CSV text file?

Upvotes: 2

Views: 3633

Answers (1)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

The problem with your code is that you are printing the string "tweets", instead I believe you meant to print the value of the variable tweets. So the change that is needed is to remove the double quotes around "tweets":

CSV.open("trial.csv", "ab") do |csv|
  csv << ["text", "created_at", "name", 'id']
  csv << [tweets]  # <- NOTE the change here 
  end
end

Upvotes: 1

Related Questions