15

How to store a Ruby array into a file?

2
  • Your question is unclear, are you asking how to define an array as part of ruby source code, or how to serialize an array on the disk ? Commented Jul 22, 2010 at 11:58
  • I am talking about the latter. Commented Jul 22, 2010 at 12:06

7 Answers 7

18

I am not sure what exactly you want, but, to serialize an array, write it to a file and read back, you can use this:

fruits = %w{mango banana apple guava}
=> ["mango", "banana", "apple", "guava"]
serialized_array = Marshal.dump(fruits)
=> "\004\b[\t\"\nmango\"\vbanana\"\napple\"\nguava"
File.open('/tmp/fruits_file.txt', 'w') {|f| f.write(serialized_array) }
=> 33
# read the file back
fruits = Marshal.load File.read('/tmp/fruits_file.txt')
=> ["mango", "banana", "apple", "guava"]

There are other alternatives you can explore, like json and YAML.

Sign up to request clarification or add additional context in comments.

Comments

8

To just dump the array to a file in the standard [a,b,c] format:

require 'pp'
$stdout = File.open('path/to/file.txt', 'w')
pp myArray

That might not be so helpful, perhaps you might want to read it back? In that case you could use json. Install using rubygems with gem install json.

require 'rubygems'
require 'json'
$stdout = File.open('path/to/file.txt', 'w')
puts myArray.to_json

Read it back:

require 'rubygems'
require 'json'
buffer = File.open('path/to/file.txt', 'r').read
myArray = JSON.parse(buffer)

Comments

6

There are multiple ways to dump an array to disk. You need to decide if you want to serialize in a binary format or in a text format.

For binary serialization you can look at Marshal

For text format you can use json, yaml, xml (with rexml, builder, ... ) , ...

Comments

2

Some standard options for serializing data in Ruby:

(There are other, arguably better/faster implementations of YAML and JSON, but I'm linking to built-ins for a start.)

In practice, I seem to see YAML most often, but that may not be indicative of anything real.

5 Comments

nice, I didn't know JSON was built into ruby 1.9 now
@ghoppe - yeah, I should mention that in an edit. I actually prefer to use yajl-json - it's speedy - but I didn't want to clutter the answer.
I believe they did some work to make YAML be a superset of JSON. You might be able to parse JSON with a YAML parser when using Ruby 1.8.
@Benjamin Oakes: that's true as of YAML 1.2. However, the builtin YAML parser/emitter in Ruby 1.8 and 1.9.1 is based on an older version of the specification which is not a proper superset of JSON. Even worse: it's not even spec-compliant. This only changes in Ruby 1.9.2.
@Jörg W Mittag: Really? That's good to know. I've only used YAML for somewhat simple stuff, so I haven't run into the spec problems.
1

Here's a quick yaml example

config = {"rank" => "Admiral", "name"=>"Akbar",
          "wallet_value" => 9, "bills" => [5,1,1,2]}

open('store.yml', 'w') {|f| YAML.dump(config, f)}
loaded = open('store.yml') {|f| YAML.load(f) }
p loaded 
# => {"name"=>"Akbar", "wallet_value"=>9,  \
#  "bills"=>[5, 1, 1,   2], "rank"=>"Admiral"}

1 Comment

yaml format is slower than json, and json is slower than Marshal see skorks.com/2010/04/… so use Marshal or json for large objects.
1

Example: write text_area to a file where text_area is an array of strings.

File.open('output.txt', 'w') { |f| text_area.each { |line| f << line } }

Don't forget to do error checking on file operations :)

Comments

0

Afaik.. files contain lines not arrays. When you read the files, the data can then be stored in an array or other data structures. I am anxious to know if there is another way.

1 Comment

You can serialize data structures, save them to a file and them load them back up later. It's a standard way to do light-weight quasi-databases for simple things. Also, I would say that "lines" is already a relatively high level of abstraction for what files hold - it's a human-centric, text-centric way of viewing it. But that's being nit-picky.

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.