Thursday, June 21, 2012

Ruby string manipulation: struct, split, join

Every time I write ruby it seems like I have to re-learn everything. To shortcut the process for next time here is a snippet that demonstrates some string handling by parsing the output of lsof (OS X format). Ruby structs are the equivalent of python namedtuple, very handy for splitting up strings in a sane way.
def parse_lsof(lsof_out)
  net_listener
= Struct.new(:command, :pid, :user, :fd, :type, :device, :size, :node, :name, :status)
  output
= []

 
# strip header line
  lsof_lines
= lsof_out.split("\n")[1..-1]

  lsof_lines
.each {
   
|line|

    line_array
= line.split("\s")
    listener_o
= net_listener.new(*line_array)
    output
.push("#{listener_o.command},#{listener_o.user},#{listener_o.type},#{listener_o.node},#{listener_o.name}")
 
}
 
return output.join("    ")
end

No comments: