Skip to content

Instantly share code, notes, and snippets.

@louis-wu
Created May 17, 2010 09:41
Show Gist options
  • Save louis-wu/403597 to your computer and use it in GitHub Desktop.
Save louis-wu/403597 to your computer and use it in GitHub Desktop.
YAML
#---
#YAML is a format for representing objects as strings.
#YAML is nice because it’s human-readable
#---
#YAML::dump: convert your Person object array into YAML data
>> require 'yaml'
=> true
>> class Person
>> attr_accessor :name, :age
>> end
=> nil
>> fred = Person.new
=> #<Person:0x7fed8bc0>
>> fred.name = "Fred Bloggs"
=> "Fred Bloggs"
>> fred.age = 45
=> 45
>> laura = Person.new
=> #<Person:0x7fec7604>
>> laura.name = "Laura Smith"
=> "Laura Smith"
>> laura.age = 23
=> 23
>> test_data = [ fred, laura ]
=> [#<Person:0x7fed8bc0 @name="Fred Bloggs", @age=45>, #<Person:0x7fec7604 @name="Laura Smith", @age=23>]
>> puts YAML::dump(test_data)
---
- !ruby/object:Person
age: 45
name: Fred Bloggs
- !ruby/object:Person
age: 23
name: Laura Smith
=> nil
#YAML::load: turn YAML code into working Ruby objects.
>> require 'yaml'
=> false
>> class Person
>> attr_accessor :name, :age
>> end
=> nil
>> yaml_string = <<END_OF_DATA
---
- !ruby/object:Person
age: 45
name: Fred Bloggs
- !ruby/object:Person
age: 23
name: Laura Smith
END_OF_DATA
=> "---\n- !ruby/object:Person\n age: 45\n name: Fred Bloggs\n- !ruby/object:Person\n age: 23\n name: Laura Smith\n"
>> test_data = YAML::load(yaml_string)
=> [#<Person:0x7fe71d94 @name="Fred Bloggs", @age=45>, #<Person:0x7fe71ac4 @name="Laura Smith", @age=23>]
>> puts test_data[0].name
Fred Bloggs
>> require 'yaml'
=> true
#用array存放一些字符,然后把array转化成yaml字符格式。
>> test_array = ['louis', 'steven', 'john']
=> ["louis", "steven", "john"]
>> test_string = test_array.to_yaml
=> "--- \n- louis\n- steven\n- john\n"
#新建一个.txt文件,把yaml字符写入该文件
>> filename = 'myfriends.txt'
=> "myfriends.txt"
>> File.open filename, 'w' do |f|
?> f.write test_string
>> end
=> 29
#从.txt文件中读取yaml字符,然后通过YAML:load转化为array
>> read_string = File.read filename
=> "--- \n- louis\n- steven\n- john\n"
>> read_array = YAML::load read_string
=> ["louis", "steven", "john"]
#看看YAML字符像什么
>> puts read_string
---
- louis
- steven
- john
#在下面的程序中,我们写2个methods,完成对象的存储和读取
>> require 'yaml'
=> false
# 我们先定义一个方法,把对象存入文件...
>> def yaml_save object, filename
>> File.open filename, 'w' do |f|
?> f.write(object.to_yaml)
>> end
>> end
#我们再定义一个方法,把文件字符存入array
>> def yaml_load filename
>> yaml_string = File.read filename
>> YAML::load yaml_string
>> end
# ...现在,我们使用上面定义的方法.
>> test_array = ['cat', 'dog', 'duck']
=> ["cat", "dog", "duck"]
>> filename = 'JiaQing.txt'
=> "JiaQing.txt"
# 我们把对象存入文件...
>> yaml_save test_array, filename
# 我们装载文件...
>> read_array = yaml_load filename
=> ["cat", "dog", "duck"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment