From: Dan Zwell Date: 2007-08-29T15:25:59+09:00 Subject: Re: Help parsing simple structured data. Nuby Ruby wrote: > Dan, > > That works perfectly, thank you a lot! This type of data I end up dealing > with day-in and day-out, and this will help a lot. > > Craig > > On 8/28/07, Dan Zwell wrote: >> Nuby Ruby wrote: >>> I'm rather new to Ruby and am trying to figure out how to parse some >>> structured data.. This is pretty much the most common problem I run into >>> and it'd be *really* helpful to see an example to wrap my head around >> blocks >>> & hashes >>> >>> The data I'm working with is the output of `df -h` which looks like this >> : >>> >>> Filesystem Size Used Avail Use% Mounted on >>> /dev/md0 9.9G 1.6G 7.8G 17% / >>> /dev/md1 60G 154M 57G 1% /data >>> /dev/sda1 99M 12M 83M 13% /boot >>> >>> In the end what I'd like to end up with is to be able to say print >>> hash[md0(size)] and have it >>> return 9.9G or hash[sda1(Mount)] and have it show the mountpoint of >> /boot >>> If anyone could help I'd really appreciate it. >>> >>> Craig >>> >> Try this: >> >> rows = `df -h`.split("\n")[1..-1] >> hash = Hash.new {|hash, key| hash[key] = {}} >> rows.each do |row| >> data = row.split /\s+/ >> device = data[0].sub(%r|^/dev/|, "") >> %w{size used avail use mount}.each_with_index do |field, column| >> hash[device][field] = data[column+1] >> end >> end >> >> After running it, you should be able to find your data in >> hash["md0"]["size"] or hash["sda1"]["mount"]. >> >> Does this work for you? >> >> Dan >> >> > Craig, By the way, I just realized that my script assumes that the mount point has no spaces. Nothing horrible will happen if it does, but hash[device]["mount"] will only contain the first word, like "/d/My" of "/d/My Documents". If you want to fix that, you could replace a few of the lines in the above script with these: >> %w{size used avail use}.each_with_index do |field, column| >> hash[device][field] = data[column+1] >> end >> hash[device][mount] = data[5..-1].join(" ") Have fun, Dan