Advertisement
Guest User

Untitled

a guest
May 24th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. require "nokogiri"
  2.  
  3. # 1) What is your favorite Ruby class/library or method and why?
  4. # I will say pry, really handy gem to inspect code and dig while debugging.
  5.  
  6. # 2) Given HTML: "<div class="images"><img src="/pic.jpg"></div>" Using Nokogiri how would you select the src attribute from
  7. # the image? Show me two different ways to do that correctly the the HTML given.
  8. html = Nokogiri::HTML("<div class='images'><img src='/pic.jpg'></div>")
  9. src_1 = html.xpath("//div/img/@src").first.value # => "/pic.jpg"
  10. src_2 = html.css("div[class='images'] img").attr("src").value # =>"/pic.jpg"
  11.  
  12. # 3) If found HTML was a collection of li tags within a div with class="attr"
  13. # how would you use Nokogiri to collect that information into one array?
  14. html = Nokogiri::HTML("<div class='attr'><ul><li>batman</li><li>the joker</li></ul></div>")
  15. info = html.xpath("//div[@class='attr']//ul//li").map(&:text) # => ["batman", "the joker"]
  16.  
  17. #4) Please collect all of the data presented into a key-value store. Please include code and the output.
  18. # Given the following HTML:
  19. html = Nokogiri::HTML(<<-HTML
  20. <div class='listing'>
  21. <div class='row'>
  22. <span class='left'>Title:</span>
  23. <span class='right'>The Well-Grounded Rubyist</span>
  24. </div>
  25. <div class='row'>
  26. <span class='left'>Author:</span>
  27. <span class='right'>David A. Black</span>
  28. </div>
  29. <div class='row'>
  30. <span class='left'>Price:</span>
  31. <span class='right'>$34.99</span>
  32. </div>
  33. <div class='row'>
  34. <span class='left'>Description:</span>
  35. <span class='right'>A great book for Rubyists</span>
  36. </div>
  37. <div class='row'>
  38. <span class='left'>Seller:</span>
  39. <span class='right'>Ruby Scholar</span>
  40. </div>
  41. </div>
  42. HTML
  43. )
  44.  
  45. data = {}
  46. html.xpath("//div[@class='listing']//div[@class='row']").each do |node|
  47. key = node.at('.left').text.gsub(":", "")
  48. value = node.at('.right').text
  49. data[key] = value
  50. end
  51.  
  52. # data =>
  53. # {
  54. # "Title" => "The Well-Grounded Rubyist",
  55. # "Author" => "David A. Black",
  56. # "Price" => "$34.99",
  57. # "Description" => "A great book for Rubyists",
  58. # "Seller" => "Ruby Scholar"
  59. # }
  60.  
  61. # 5) What Ruby feature do you hate?
  62. # No parallel threading in MRI (GIL)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement