Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and updating YAML file by ruby code

I have written a yml file like this:

last_update: '2014-01-28 11:00:00'

I am reading this file as

config = YAML.load('config/data.yml')

Later I am accessing the last_update_time as config['last_update'] but it is not working. Also I want to update last_update_time by my ruby code like it should update like:

 last_update: '2014-01-29 23:59:59' 

I have no idea how to do that.

like image 602
Joy Avatar asked Jan 29 '14 05:01

Joy


People also ask

How do I read a YAML file in Ruby?

yml file into the Ruby language, we have utilized the load file method. The object is created as fruit_array, which has the YAML load file method. Inside that method, we have invoked the read function that inputs the fruits. yml file as a parameter.

Can you use regex in YAML file?

If you need to specify a regular expression in a YAML file, it's a good idea to wrap the regular expression in single quotation marks to work around YAML's tricky rules for string escaping.

What is Ruby YAML used for?

We can use YAML files in conjunction with our Ruby program to store objects, and in the case of web browsing, maintain state by storing data that persists in external files. Additionally, by overwriting YAML files, we can modify the values inside of our stored Ruby objects.

Is YAML a config file?

YAML is a data serialization language that is often used for writing configuration files. Depending on whom you ask, YAML stands for yet another markup language or YAML ain't markup language (a recursive acronym), which emphasizes that YAML is for data, not documents.


1 Answers

Switch .load to .load_file and you should be good to go.

#!/usr/bin/env ruby
require 'yaml'
config = YAML.load_file('data.yml')
puts config['last_update']

After running this is what I get

orcus:~ user$ ruby test.rb
# ⇒ some_data

To write the file you will need to open the YAML file and write to the handle. Something like this should work.

require 'yaml'
config = YAML.load_file('data.yml')
puts config['last_update'] #in my file this is set to "some data"
config['last_update'] = "other data"
File.open('data.yml','w') do |h| 
   h.write config.to_yaml
end

Output was

orcus:~ user$ ruby test.rb
some data
orcus:~ user$ cat data.yml
---
last_update: other data
like image 198
Phobos Avatar answered Oct 20 '22 01:10

Phobos