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
Best Way to Use HTML5 Data Attributes with Rails Content_Tag Helper
Ruby Imap "Changes" Since Last Check
Accessing Headers from Sinatra
Hash Remove All Except Specific Keys
Deadlock Detected with Capybara-Webkit
Are There "Rules" for Ruby Syntactic Sugar
Rails 3:Do I Need to Give Return True in a Before_Save Callback for an Object.Save to Work
Rounding a Float to the Nearest Integer in Ruby
How to Redirect Back to a Page I'M Currently On
Change The Ruby Process Name in Top
Ruby Metaprogramming, How Does Rspec's 'Should' Work
How to Specify a Minimum Ruby Version in a Gemspec
How to Read from Redis Inside a Multi Block in Ruby
Rspec Load Time Incredible Long on Os X
How to Programmatically Take Snapshot of Crawled Webpages (In Ruby)