在 YAML 中存储信息
我查看了 YAML for ruby 文档,但找不到答案。
我有一份几名员工的名单。每个人都有姓名、电话和电子邮件:
Employees:
Name | Phone | Email
john 111 [email protected]
joe 123 [email protected]
joan 321 [email protected]
我如何在 YAML 中编写上述信息才能得到以下 ruby 输出?
employees = [ {:name => 'john', :phone => '111', :email => '[email protected]'}, {:name => 'joe', :phone => '123', :email => '[email protected]'}, {:name => 'joan', :phone => '321', :email => '[email protected]'} ]
这就是我解析 YAML 文件的方式:
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")
谢谢!
I looked through the YAML for ruby documentation and couldn't find an answer.
I have a list of several employees. Each has a name, phone, and email as such:
Employees:
Name | Phone | Email
john 111 [email protected]
joe 123 [email protected]
joan 321 [email protected]
How would I write the above information in YAML to end up with the following ruby output?
employees = [ {:name => 'john', :phone => '111', :email => '[email protected]'}, {:name => 'joe', :phone => '123', :email => '[email protected]'}, {:name => 'joan', :phone => '321', :email => '[email protected]'} ]
This is how I parse the YAML file:
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
输出是字符串键,而不是符号键,但如果确实有必要,您可以自己进行转换。
Output is string keys, not symbol keys, but you can make that conversion yourself if really necessary.
请注意,Ruby 1.8.6 附带的标准 yaml 不 UTF / Unicode 安全。
如果您要进行任何非 ASCII 测试,请使用 Ruby 1.9 yaml 或 Ya2YAML gem。
此外,查看 yaml 输入应该是什么的最简单方法是创建(在 Ruby irb 中)数据结构的示例。然后使用 .to_yaml 对象类方法将其转换为 yaml 文本。
例如
Note that standard yaml which ships with Ruby 1.8.6 is NOT UTF / Unicode safe.
Use either Ruby 1.9 yaml or Ya2YAML gem if you'll have any non-ASCII test.
Also, the easiest way to see what the yaml input should be is to create (in Ruby irb), an example of your data structure. Then turn it into yaml text by using the .to_yaml object class method.
Eg