Skip to content

Instantly share code, notes, and snippets.

@dvoryankin
Created August 18, 2016 17:44
Show Gist options
  • Save dvoryankin/f6784fc326567757d0821941aba677c2 to your computer and use it in GitHub Desktop.
Save dvoryankin/f6784fc326567757d0821941aba677c2 to your computer and use it in GitHub Desktop.
require "nokogiri"
# 1) What is your favorite Ruby class/library or method and why?
# 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 HTML given.
html = Nokogiri::HTML('<div class="images"><img src="/pic.jpg"></div>')
w1 = html.css('img')[0]['src'] # => "/pic.jpg"
w2 = html.xpath('//img/@src') # => "/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>first</li><li>second</li></ul></div>")
arr = html.xpath("//div[@class='attr']//ul//li").map(&:text) # => ["first", "second"]
#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
)
hash = {}
html.css('.row').map do |row|
hash[row.css('.left').text.to_sym]=row.css('.right').text
end
hash.each { |key, value| puts "#{key} #{value}" }
# =>
# 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?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment