【Ruby】【YAML】

require "YAML"

var = YAML.load(File.open('b.yml'))

#哈希
puts var.class #Hash
print var ,"\n" #{"data"=>{"list"=>["Item1", "Item2", "Item3"], "hash"=>{"key1"=>"value1", "key2"=>"value2", "key3"=>"value3"}}}

print var["data"].class,"\n" #Hash
print var["data"],"\n" #{"list"=>["Item1", "Item2", "Item3"], "hash"=>{"key1"=>"value1", "key2"=>"value2", "key3"=>"value3"}}

print var["data"]["hash"].class,"\n" #Hash
print var["data"]["hash"],"\n" #{"key1"=>"value1", "key2"=>"value2", "key3"=>"value3"}

#列表
print var["data"]["list"].class #Array
print var["data"]["list"] ,"\n" #Array["Item1","Item2","Item3"]

#字符串和其他类型
=begin
YAML会自动判断类型。一般性的文字都会被解析成字符串。在有可能发生歧义的情况下,可为字符串加上单引号或者双引号
=end

print var["data"]["str"].class,"\n" #Hash
print var["data"]["str"],"\n" #1=>1.0, 1.0=>"1.0", "1.0"=>#<Date: 2006-01-01 ((2453737j,0s,0n),+0s,2299161j)>}

#字符串块
=begin
用| 表示保留换行符
用>表示删除换行符
=end
print var["data"]["strBone"].class,"\n"
print var["data"]["strBone"]
print var["data"]["strBone2"].class,"\n"
print var["data"]["strBone2"]
=begin
String
this is line1.
this is line2.
this is line3.
String
Hello, world.
=end

# 完整的例子 对于重复出现的项目,可以用&进行定义,然后用*进行引用
var2 = YAML.load(File.open("abc.yml"))

print var2.class,"\n" #Hash
print var2
=begin
{
"items"=>[
{"price"=>1.47, "quantity"=>4, "part_no"=>"A4786", "descrip"=>"Water Bucket (Filled)"},
{"price"=>100.27, "quantity"=>1, "part_no"=>"E1628", "descrip"=>"High Heeled /"Ruby/" Slippers"}
],
"bill-to"=>{"city"=>"East Westville", "street"=>"123 Tornado Alley/nSuite 16/n", "state"=>"KA"},
"specialDelivery"=>"Follow the Yellow Brick Road to the Emerald City. Pay no attention to the man behind the curtain.",
"date"=>#<Date: 4908637/2,0,2299161>,
"ship-to"=>{"city"=>"East Westville", "street"=>"123 Tornado Alley/nSuite 16/n", "state"=>"KA"},
"customer"=>{"given"=>"Dorothy", "family"=>"Gale"},
"logEvent"=>"Purchase Invoice"
}
=end

【b.yml】
data:
list:
- Item1
- Item2
- Item3

hash:
key1: value1
key2: value2
key3: value3

str:
1: 1.0
1.0: "1.0"
"1.0": 2006-01-01

strBone:
|
this is line1.
this is line2.
this is line3.

strBone2:
>
Hello,
world.








【abc.yml】
logEvent: Purchase Invoice
date: 2018-07-12
customer:
given: Dorothy
family: Gale

bill-to: &id001
street: |
123 Tomado Alley
Suite 16
city: East Westvile
state: KA

ship-to: *id001

items:
- part_no: A476
descrip: Water Bucket(Filled)
price: 1.47
quantity: 4

- part_no: E1628
descrip: High Heeled "Ruby" Slippers
price: 100.27
quantity: 1

specialDelivery: >
Follow the yellow Brick
Road to the Emeraid City.
Pay no attention to the
man being the curtain.

















猜你喜欢

转载自www.cnblogs.com/suren2017/p/9297576.html