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
:
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
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”].
structured data… This is pretty much the most common problem I run into
/dev/sda1 99M 12M 83M 13% /boot
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(" ")
In my situation it’ll always be safe to assume there are no mount
points,
but I’ll grab your code anyways in case I ever run it on a windows or
mac
box.
BTW, here’s the code I’m working on, thanks for the tidbit, this little
bit
of processing is the bit of code I use most in my daily life, and the
hardest for me to wrap my head around when I play with new langauges.
hash = Hash.new {|hash, key| hash[key] = {}}
disks.each do |disk|
data = disk.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
Oh man this is awesome. I love ruby, I spent the last hour playing with
ruport, and am in love with it’s simplicity… The reason I’m learning
Ruby
is to make it easier for me to get off my butt and write reports.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.