InQusitive InQusitive - 1 month ago 4
Ruby Question

How to use descendants

I have something like:

doc.css('results[name="test"]').map { |node| file.write node.ancestors("tests").first['name']; file.write "\n" }


But what I want to write is:

doc.css('tests').map{ |node| file.write node.first['name'] if node.descendants('results').first['name'] == "test" }


But there is no method
descendants
.
If I want go with the second approach what should I modify in the snippet?

Answer

Try

doc.css('tests').each { |node| file.write node['name'] if node.css('results[name="test"]').any? }

or

doc.css('tests').select { |node| node.css('results[name="test"]').any? }.each { |node| file.write node['name'] }