Curtis Miller Curtis Miller - 1 month ago 4
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;">
<tbody>
<tr class="team-member odd" row="1" team="0" data-id="66c36a98-7832-11e0-968b-5e9370556780" name="Barbara Gordon">
</tr>
<tr class="team-member even" row="5" team="0" data-id="a9042cb6-7527-11e0-9a7d-00b7c9f2a9c6" name="Bruce Wayne">
</tr>
<tr class="team-member even" row="0" team="0" data-id="39daacee-7832-11e0-968b-5e9370556780" name="Dick Grayson">
</tr>
</tr>
</tbody>
</table>



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

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 = REXML::Document.new(my_table_data)
doc.elements.each('table/tbody/tr') do |el|
  names << el.attributes['name'] if el.attributes['name']
end
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']
end
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...