cyborg
cyborg

Reputation: 878

How to collect entries from a YAML file?

I have YAML files like the following:

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

I need to collect the titles whose associated description is not present, for example from the file above I need to collect the title "Star Performer". How can I achieve this?

Upvotes: 2

Views: 505

Answers (1)

Richard Jordan
Richard Jordan

Reputation: 8202

If you mean by filter you want to collect those titles

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

Per the comment of toro2k if you're using Rails you can substitute blank? for empty? to cover cases where there is no description key present.

Also this will give you an array positions_with_no_description that includes nil values. To eliminate them just call compact!

A concise version of the above could be:

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

I have tested this on your test yml file and it works. The error was I had mistakenly used "position_details" whereas you'd put "position details" as your key - no underscore.

My exact code from IRB where I just tested this:

> 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"]

Upvotes: 4

Related Questions