Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically create a 2D array in Ruby?

Tags:

ruby

nokogiri

So I am parsing a URL and want to get a list of all the links in a page using Nokogiri.

But I want to push the results returned into a two-dimensional array.

I am now doing this:

def my_list(url)
    root = Nokogiri::HTML(open(url))
    list = []

    root.css("a").each do |link|
        list << (link[:href])           
    end

end

This gives me just the http links. If I do list << link it gives me the full <a> tag.

What I want to do is to push just the text of the link (can use link.text) to say list[0][0], and then the href value (using link[:href]) to the other cell say list[0][1].

How do I do that?

Thanks.

like image 718
marcamillion Avatar asked Apr 12 '26 06:04

marcamillion


2 Answers

def my_list(url)
  root = Nokogiri::HTML(open(url))
  root.css("a").map do |link|
    [link.text, link[:href]]           
  end
end
like image 90
fl00r Avatar answered Apr 14 '26 22:04

fl00r


def my_list(url)
    root = Nokogiri::HTML(open(url))
    list = []

    root.css("a").each do |link|
        list << [link.text,link[:href]]           
    end

end
like image 43
SwiftMango Avatar answered Apr 14 '26 22:04

SwiftMango



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!