Radek
Radek

Reputation: 11121

save/edit array in and outside 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

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

Upvotes: 3

Views: 712

Answers (4)

Kim Stebel
Kim Stebel

Reputation: 42047

If I understand correctly, you have a two-dimensional array. You could output it in csv format like so:

array.each do |row|
    puts row.join(",")
end

Then you import it with Calc to edit it or just use a text editor.

If your data might contain commas, you should have a look at the csv module instead: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

Upvotes: 0

paradigmatic
paradigmatic

Reputation: 40461

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.

Upvotes: 2

johannes
johannes

Reputation: 7272

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.

Upvotes: 7

ryeguy
ryeguy

Reputation: 66861

You could serialize it to json and save it to a file. This would allow you to edit it using a simple text editor.

if you want to edit it in something like calc, you could consider generating a CSV (comma separated values) file and import it.

Upvotes: 1

Related Questions