How do I write the contents of a hash to a file in Ruby?
This should work for you. I would recommend reading up more on Files and iterating through hashes yourself first though.
yourfile = "/some/path/file.txt"
File.open(yourfile, 'w') do |file|
character.each{ |k, v| file.write("#{k}: #{v}\n") }
end
Reading a hash from a file on disk
The proper way to save simple data structures to a file is to serialize them. In this particular case, using JSON is probably a good choice:
# save hash to file:
f.write MultiJson.dump(my_hash)
# load it back:
p MultiJson.load(file_contents)
Keep in mind that JSON is only able to serialize simple, built-in data types (strings, numbers, arrays, hashes and the like). You will not be able to serialize and deserialize custom objects this way without some additional work.
If you don't have MultiJson
, try it with JSON
instead.
Ruby on Rails write Hash to file without : and = values
As I said in comments, you have to do this manually. Use hash.map
to get key/value pairs and format them accordingly, join using commas, then add the curlies around the result. I use #to_json
as a shortcut to add quotes to strings but not to integers.
hash = {emp_id:15, emp_name:"Test", emp_sal:1800, emp_currency:"USD"}
require 'json'
result = '{' + hash.map { |k, v| "#{k}:#{v.to_json}" }.join(', ') + '}'
puts result
# => {emp_id:15, emp_name:"Test", emp_sal:1800, emp_currency:"USD"}
Note that this only works on a single level. If you have nesting, a recursive function will be needed.
How do I save settings as a hash in a external file?
The most common way to store configuration data in Ruby is to use YAML:
settings.yml
user1:
path: /
days: 5
user2:
path: /tmp/
days: 3
Then load it in your code like this:
require 'yaml'
settings = YAML::load_file "settings.yml"
puts settings.inspect
You can create the YAML file using to_yaml
:
File.open("settings.yml", "w") do |file|
file.write settings.to_yaml
end
That said, you can include straight Ruby code also, using load
:
load "settings.rb"
However, you can't access local variables outside the file, so you would have to change your code to use an instance variable or a global variable:
settings.rb
SETTINGS = {
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' => '/tmp/','days' => '3' }
}
@settings = { 'foo' => 1, 'bar' => 2 }
Then load it thus:
load "settings.rb"
puts SETTINGS.inspect
puts @settings.inspect
Loop through a hash and save to a different row
Try this:
CSV.generate(col_sep: ';', headers: LOG_HEADERS, encoding: 'UTF-8', write_headers: true) do |csv|
hsh.each do |key,value|
row = []
value.each do |v|
row << "{#{key}: #{v}}"
end
csv << row
end
end
Related Topics
If(!X) VS If(X==False) in Ruby
Mailchimp API Not Replacing Mc:Edit Content Sections (Using Ruby Library)
Rails ( Set_No_Cache Method) Cannot Disable Browser Caching in Safari and Opera
Ruby Variable Name with Double Underscores
Activerecord Connection Warning. (Database Connections Will Not Be Closed Automatically)
How to Remove Non-Printable/Invisible Characters in Ruby
Testing Routes with Subdomain Constraints Using Rspec
How to Get a Selenium/Ruby Bot to Wait Before Performing an Action
What Is the Purpose of 'Kernel'
Generate Activerecord Schema from an Existing Table
How to More Elegantly Remove Duplicate Items Across All Elements of a Ruby Array
Eliminate Consecutive Duplicates of List Elements
How to Decode a Cookie from the Header of a Websocket Connection Handshake? (Ruby)
Sinatra Does Not Start with Twitter Gem
Ruby/Pgsql Error on Rails Start:Cannot Load Such File -- Pg_Ext (Loaderror)