【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.

















转载于:https://www.cnblogs.com/suren2017/p/9297576.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值