You can call first on an empty array, the problem is that it will return nil , and you cannot say nil['src'] without getting sad. You can do it:
src = (element.ancestors('table').first || { })['src']
And if you are in Rails, you can use try as follows:
src = element.ancestors('table').first.try(:fetch, 'src')
If you do so much, then hide the ugliness in the method:
def closest_attr_from(e, selector, attr) a = e.closest(selector) a ? a[attr] : nil end
and then
src = closest_attr_from(element, 'table', 'src')
You can also install it directly in Nokogiri :: XML :: Node (but I would not recommend it):
class Nokogiri::XML::Node def closest(selector) ancestors(selector).first end def closest_attr(selector, attr) a = closest(selector) a ? a[attr] : nil end end
source share