问题描述
我有这样一个 YAML 文件:
I have such a YAML file:
Company1:
name: Something1
established: 2000
#
Company2:
name: Something2
established: 1932
读取 YAML 文件:(** UPDATE **)
reading the YAML file: (** UPDATE **)
config = YAML.load_file('file.yaml')
config.each do |key, value|
if(key == 'name')
company_name = value
#year = config['Company1']['established']
year = config.fetch(key)['established']
end
end
** 更新 **现在上面的代码可以工作了,但结果显示为:
** UPDATE **Now the above code is working, but it shows the result as:
company1 => {"name" => "something1"} => {"established year" => 2000"}
如何删除 {} 和 "" ?
how can I remove the the {} and "" ?
推荐答案
好的,这是您的 YAML 文件吧?
Okay, so this is your YAML file right?
Company1:
name: Something1
established: 2000
Company2:
name: Something2
established: 1932
好的,现在这个 YAML 文件实际上代表了一个哈希.The has 有两个键,即 Company1、Company2(因为它们是前导条目,并且子条目(名称和已建立)在它们下方缩进).这两个键的值又是一个哈希值.这个 Hash 也有 2 个键,即 name 和 created.它们分别具有Something1和2000等值.
Okay now this YAML file actually represents a Hash. The has has two keys i.e Company1, Company2 (because they are the leading entries and the sub entries (name and established) are indented under them). The value of these two keys is again a Hash. This Hash also has 2 keys namely name and established. And they have values like Something1 and 2000 respectively etc.
所以当你这样做时,
config=YAML.load_file('file.yml')
并使用,
puts config
你得到以下输出:
{"Company1"=>{"name"=>"Something1", "established"=>2000}, "Company2"=>{"name"=>"Something2", "established"=>1932}}
所以我们有一个由 YAML 文件描述的 Hash 对象.
So we have a Hash object as described by the YAML file.
使用这个哈希非常简单.
Using this Hash is pretty straight forward.
由于每个公司的名称和年份都在由外部哈希(company1、company2)保存的单独哈希中,我们可以遍历这些公司.以下代码打印哈希.
Since each company's name and year come in a separate hash held by the outer hash (company1, company2), we can iterate through the companies. The following Code prints the Hash.
config.each do |company,details|
puts company
puts "-------"
puts "Name: " + details["name"]
puts "Established: " + details["established"].to_s
puts "\n\n"
end
所以在每次迭代中,我们可以访问哈希的每个(键,值).在第一次迭代中,我们将 company
(key) 作为 Company1
和 details
(value) 作为 {"name"=>"东西1",建立"=>2000}
So in Each iteration we get access to each (key,value) of the Hash. This in first iteration we have company
(key) as Company1
and details
(value) as {"name"=>"Something1", "established"=>2000}
希望这有帮助.
这篇关于如何读取 YAML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!