tags:

views:

166

answers:

2

Hi i have a yaml file like so

---
data:
  - date: "2004-06-11"
    description: First description

  - date: "2008-01-12"
    description: Another descripion

How can i do a "ypath" query similar to xpath for xml ? Something like "get the description where the date is 2004-06-11"

YAML.parse_file('myfile.yml').select('/data/*/date == 2004-06-11')

How do you do it, and if that's possible how can i similarly edit the description by 'ypath' ?

Thanks

+1  A: 

The yaml file describes a hash mapping from strings to arrays of hashes that map from strings to strings. There is no such thing as xpath for nested hashes (at least not in the standard library), but it's simple enough with standard Hash and Enumerable methods:

hash = YAML.load_file('myfile.yml')
item = hash["data"].find {|inner_hash| inner_hash["date"] == "2004-06-11"}
#=> {"date"=>"2004-06-11", "description"=>"First description"}

To change the description, you can then simply do item["description"] = "new description" and then serialize the hash back to YAML using hash.to_yaml.

sepp2k
+1  A: 

If Ruby is not a hard constraint you might take a look at the dpath tool. It provides an xpath-like query language to YAML (and other) files. Maybe call it externally to filter your data.

Renormalist