How to Store a Ruby Array into a File

how to store a Ruby array into a file?

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

Add each array element to the lines of a file in ruby

Either use Array#each to iterate over your array and call IO#puts to write each element to the file (puts adds a record separator, typically a newline character):

File.open("test.txt", "w+") do |f|
a.each { |element| f.puts(element) }
end

Or pass the whole array to puts:

File.open("test.txt", "w+") do |f|
f.puts(a)
end

From the documentation:

If called with an array argument, writes each element on a new line.

Write array to file ruby

You almost had it!

File.open('brands.txt', 'w') do |file| 
brands.each_with_index do |brand, index|
file.print "#{brand.name} - #{brand.url}"
end
end

Break text file into separate words and store in array in Ruby

Yes. Either do:

text_file.push(*line.split.map(&:to_s))

or:

text_file.concat(line.split.map(&:to_s))

how to write an array to file in ruby

Check the File class.

File.open(yourfile, 'w') { |file| file.write(":#{your_array.join(',')}") }

If you want to append text to the file, you need to open the file in "append" mode.

File.open(yourfile, 'a') { |file| file.write(":#{your_array.join(',')}") }

How to read an array from a file and store it in an array

You will need to use Kernel#eval to parse the file contents (string) as Ruby code.

Contents of eval.txt:

['abc', 'def']

Ruby code:

contents = File.read("eval.txt")
foo = Kernel.eval(contents)
puts "Length of foo is #{foo.length}"

Outputs:

Length of foo is 2

Using JSON as your serialization format might be saner option though.

Writing array into csv file

How about this? CSV creation outside the results loop.

require 'tiny_tds'
require 'csv'

db_host = 'myserver.com'
db_user = 'mylogin'
db_pass = 'mypassword'
client = TinyTds::Client.new(:host => db_host, :username => db_user, :password => db_pass)
results = client.execute("SELECT * FROM mydatabase")

CSV.open("data.csv", "wb") do |csv|
results.each do |row|
csv << row.to_a
end
end


Related Topics



Leave a reply



Submit