Shubham
Shubham

Reputation: 22307

how to store a Ruby array into a file?

How to store a Ruby array into a file?

Upvotes: 15

Views: 18651

Answers (7)

BrBand
BrBand

Reputation: 11

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 :)

Upvotes: 1

Paul Rubel
Paul Rubel

Reputation: 27222

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"}

Upvotes: 1

Telemachus
Telemachus

Reputation: 19705

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.

Upvotes: 2

Jean
Jean

Reputation: 21595

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, ... ) , ...

Upvotes: 6

ghoppe
ghoppe

Reputation: 21784

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)

Upvotes: 8

Swanand
Swanand

Reputation: 12426

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.

Upvotes: 18

Alok Swain
Alok Swain

Reputation: 6519

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.

Upvotes: 0

Related Questions