Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store a Ruby array into a file?

Tags:

ruby

How to store a Ruby array into a file?

like image 394
Shubham Avatar asked Jul 22 '10 11:07

Shubham


4 Answers

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.

like image 100
Swanand Avatar answered Nov 11 '22 02:11

Swanand


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)
like image 37
ghoppe Avatar answered Nov 11 '22 01:11

ghoppe


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

like image 6
Jean Avatar answered Nov 11 '22 01:11

Jean


Some standard options for serializing data in Ruby:

  • Marshal
  • YAML
  • JSON (built-in as of 1.9, various gems available as well)

(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.

like image 2
Telemachus Avatar answered Nov 11 '22 01:11

Telemachus