Reading and updating YAML file by ruby code

前端 未结 1 1259
青春惊慌失措
青春惊慌失措 2020-12-08 21:43

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(\'c         


        
相关标签:
1条回答
  • 2020-12-08 22:33

    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
    
    0 讨论(0)
提交回复
热议问题