Curtis Miller Curtis Miller - 3 years ago 72
Ruby Question

How do you create an Array from information that a Table holds in its Rows?

I have a Table that has an arbitrary amount of Rows.

In these Rows I have names that are in Columns within the Rows that I want to pull and place into an Array.

The table that I want to pull from looks like this:

<table id="team-1200d35e-7528-11e0-9a7d-00b7c9f2a9c6-table" class="grid" style="width: 748px;">
<tr class="team-member odd" row="1" team="0" data-id="66c36a98-7832-11e0-968b-5e9370556780" name="Barbara Gordon">
<tr class="team-member even" row="5" team="0" data-id="a9042cb6-7527-11e0-9a7d-00b7c9f2a9c6" name="Bruce Wayne">
<tr class="team-member even" row="0" team="0" data-id="39daacee-7832-11e0-968b-5e9370556780" name="Dick Grayson">

The Information from each row that I want to pull is the name="".

How can I pull just the names and create an array out of this?

Answer Source

Assuming your table is just a string you can parse it as an XML document using, say REXML (which appears to be a manual install), and extract the name attributes like so:

require 'rexml'
names = []
doc =
doc.elements.each('table/tbody/tr') do |el|
  names << el.attributes['name'] if el.attributes['name']
names # => ['Barbara Gordon', 'Bruce Wayne', 'Dick Grayson']

Or similarly using Nokogiri (which can be installed as a gem):

require 'nokogiri'
names = []
doc = Nokogiri::XML.fragment(my_table_data)
doc.xpath('table/tbody/tr[@name]').each do |el|
  names << el['name']
names # => ['Barbara Gordon', 'Bruce Wayne', 'Dick Grayson']

You could get fancier and split the first/last names by whitespace but that will wreak havoc for people whose first name includes a space...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download