Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require "nokogiri"
- # 1) What is your favorite Ruby class/library or method and why?
- # I will say pry, really handy gem to inspect code and dig while debugging.
- # 2) Given HTML: "<div class="images"><img src="/pic.jpg"></div>" Using Nokogiri how would you select the src attribute from
- # the image? Show me two different ways to do that correctly the the HTML given.
- html = Nokogiri::HTML("<div class='images'><img src='/pic.jpg'></div>")
- src_1 = html.xpath("//div/img/@src").first.value # => "/pic.jpg"
- src_2 = html.css("div[class='images'] img").attr("src").value # =>"/pic.jpg"
- # 3) If found HTML was a collection of li tags within a div with class="attr"
- # how would you use Nokogiri to collect that information into one array?
- html = Nokogiri::HTML("<div class='attr'><ul><li>batman</li><li>the joker</li></ul></div>")
- info = html.xpath("//div[@class='attr']//ul//li").map(&:text) # => ["batman", "the joker"]
- #4) Please collect all of the data presented into a key-value store. Please include code and the output.
- # Given the following HTML:
- html = Nokogiri::HTML(<<-HTML
- <div class='listing'>
- <div class='row'>
- <span class='left'>Title:</span>
- <span class='right'>The Well-Grounded Rubyist</span>
- </div>
- <div class='row'>
- <span class='left'>Author:</span>
- <span class='right'>David A. Black</span>
- </div>
- <div class='row'>
- <span class='left'>Price:</span>
- <span class='right'>$34.99</span>
- </div>
- <div class='row'>
- <span class='left'>Description:</span>
- <span class='right'>A great book for Rubyists</span>
- </div>
- <div class='row'>
- <span class='left'>Seller:</span>
- <span class='right'>Ruby Scholar</span>
- </div>
- </div>
- HTML
- )
- data = {}
- html.xpath("//div[@class='listing']//div[@class='row']").each do |node|
- key = node.at('.left').text.gsub(":", "")
- value = node.at('.right').text
- data[key] = value
- end
- # data =>
- # {
- # "Title" => "The Well-Grounded Rubyist",
- # "Author" => "David A. Black",
- # "Price" => "$34.99",
- # "Description" => "A great book for Rubyists",
- # "Seller" => "Ruby Scholar"
- # }
- # 5) What Ruby feature do you hate?
- # No parallel threading in MRI (GIL)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement