gustavoanalytics
gustavoanalytics

Reputation: 583

How can I puts a specific column of the array in Ruby on Rails with Nokogiri

This outputs 10 columns I want to puts these columns

i do want 3 5 9

I do not want to show the rest of the columns.

Using a values_at would work? Just not sure where to use it...

def process_page
  doc = Nokogiri::HTML(page.body)
  doc.search('#tblResults').search('tr').map{|tr| tr.search('td').map{|t| t.text}}
end

 <table>
  <% @infra.each do |post| %>
    <tr>
    <% post.each do |t| %>

      <td>
        <%= t.lstrip.html_safe %>
      </td>
    <% end %>
    </tr>
<% end %>

</table>

Upvotes: 0

Views: 84

Answers (2)

gustavoanalytics
gustavoanalytics

Reputation: 583

def process_page
      doc = Nokogiri::HTML(page.body)
     # doc.search('#tblResults').search('tr').map{|tr| tr.search('td').map{|t| t.text}}
           doc.search('#tblResults').search('tr').map{|tr| tr.search('td').to_a.values_at(3,4,8).map{|t| t.text}}
    end

Upvotes: 0

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16507

Do something like this:

def process_page
   doc = Nokogiri::HTML(page.body)
   is = [ 2,4,8 ] # accounting begins from 0
   doc.search('#tblResults').search('tr').map {|tr| tr.search('td').map.with_index {|t, i| is.include?( i ) && t.text || nil }.compact }
end

or expanding:

def process_page
   doc = Nokogiri::HTML(page.body)
   is = [ 2,4,8 ] # accounting begins from 0
   def row row
       row.map.with_index {|t, i| is.include?( i ) && t.text || nil }.compact
   end
   doc.search('#tblResults').search('tr').map {|tr| row tr.search('td') }
end

Upvotes: 1

Related Questions