Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save/edit array in and outside ruby

Tags:

ruby

I am having an array like "author","post title","date","time","post category", etc etc

I scrape the details from a forum and I want to

  • save the data using ruby
  • update the data using ruby
  • update the data using text editor or I was thinking of one of OpenOffice programs? Calc would be the best.

I guess to have some kind of SQL database would be a solution but I need quick solution for that (somthing that I can do by myself :-)

any suggestions?

Thank you

like image 260
Radek Avatar asked Jan 21 '26 01:01

Radek


2 Answers

YAML is your friend here.

require "yaml"
yaml= ["author","post title","date","time","post category"].to_yaml
File.open("filename", "w") do |f|
  f.write(yaml)
end

this will give you

---
- author
- post title
- date
- time
- post category

vice versa you get

require "yaml"
YAML.load(File.read("filename")) # => ["author","post title","date","time","post category"]

Yaml is easily human readable, so you can edit it with any text editor (not word proccessor like ooffice). You can not only searialize array's and strings. Yaml works out of the box for most ruby objects, even for objects of user defined classes. This is a good itrodution into the yaml syntax: http://yaml.kwiki.org/?YamlInFiveMinutes.

like image 82
johannes Avatar answered Jan 23 '26 16:01

johannes


If you want to use a spreadsheet, csv is the way to go. You can use the stdlib csv api like:

require 'csv'

my2DArray = [[1,2],["foo","bar"]]

File.open('data.csv', 'w') do |outfile|
  CSV::Writer.generate(outfile) do |csv|
    my2DArray.each do |row|
      csv << row
    end
  end
end

You can then open the resulting file in calc or in most statistics applications.

The same API can be used to re-import the result in ruby if you need.

like image 40
paradigmatic Avatar answered Jan 23 '26 15:01

paradigmatic