【问题标题】:How to collect entries from a YAML file?如何从 YAML 文件中收集条目?
【发布时间】:2014-02-07 08:47:52
【问题描述】:

我有如下 YAML 文件:

position_details:

  star_performer:
    title: "Star Performer"
    description: ""

  idiot of year:
    title: "idiot of year"
    description: "The Idiot of year Award recognizes excellence in anti - social  collaboration on social platform ."

我需要收集不存在关联descriptiontitles,例如从上面的文件中我需要收集标题"Star Performer"。我怎样才能做到这一点?

【问题讨论】:

  • 过滤掉是什么意思?删除它们?还给他们?将它们收集到一个数组中?
  • 过滤掉意味着以任何形式收集它们..以数组形式或列表形式。
  • 当有人解决了您的问题并回答了您的问题时 - 如下面经过全面测试的代码 - 通常被认为是接受答案的好方法。
  • 我接受 :) 谢谢大家
  • 您必须单击答案旁边的复选标记才能接受它:-)

标签: ruby-on-rails ruby yaml


【解决方案1】:

如果你的意思是过滤你想收集那些标题

data = YAML.load(File.read(File.expand_path('path/to/your.yml', __FILE__)))

positions_with_no_description = data["position_details"].each_value.collect do |pos| 
  pos["title"] if pos["description"].empty?
end

根据 toro2k 的评论,如果您使用 Rails,您可以替换空白吗?为空?涵盖不存在描述键的情况。

这也会给你一个包含 nil 值的数组positions_with_no_description。要消除它们,只需致电compact!

上述的简明版本可以是:

filtered = data["position details"]
             .each_value
             .collect { |p| p["title"] if p["description"].blank? }
             .compact!

我已经在您的测试 yml 文件上对此进行了测试,并且可以正常工作。错误是我错误地使用了"position_details",而您将“位置详细信息”作为键 - 没有下划线。

我刚刚测试过的来自 IRB 的确切代码:

> data = YAML.load(File.read(File.expand_path('../test.yml', __FILE__))
> data["position details"].each_value.collect { |x| x["title"] if x["description"].empty? }.compact!
> # => ["Star Performer"]

【讨论】:

  • 请注意,如果pos 没有description 密钥,您将获得NoMethodError。更安全的选择可能是if post['description'].nil? || pos['description'].empty?,或者,因为 OP 只使用 Rails,if post['description'].blank?
  • 正确 - 但这是针对 q 中描述的情况 - 存在描述键 - 如果它的 rails 空白很好,同意:-)
  • 嗨,Richard,nil 的未定义方法 `each_value':NilClass (NoMethodError) 即将到来
  • yaml 文件和上面一样吗?并且您已经使用 YAML.load_file 加载了它?
  • @cyborg 这段代码非常好,如果你没有得到任何方法错误,可能position_details在某个地方拼错了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 1970-01-01
相关资源
最近更新 更多