9

The content I'm scraping includes some blank elements. I either need to stop variables being set if there is no data (preferable) or just do some surgery afterwards and completely delete hashes containing blanks.

Here's my scrape code:

eqs = []

nokogiri_page.xpath('//table/tr').each do |row|
  date = row.xpath('td[1]/a/text()').text.strip
  location = row.xpath('td[5]/text()').text.strip

  eqs.push(
    date: date,
    location: location
  )
end

Some of these are blank, and I can't know which beforehand. So I tried iterating over the array and deleting blank values with:

eqs.each do |event|
  event.reject! {|k, v| v.empty? || v=="  " || v=="" }
end

This successfully removes blank keys and values, but I am still left with the empty curly braces...

Output:

[
 {},
 {},
 {},
 {
    :date=>"2016-12-14 13:19:55",
    :location=>"Myanmar"
 },
 {
    :date=>"2016-12-13 17:57:04",
    :location=>"Northern Sumatra, Indonesia"
 }
]

I want to get rid of the empty hashes completely! Anyone know what I'm getting wrong here?

3
  • If you run that array and run the same reject(&:empty?) It should do the trick Commented Dec 16, 2016 at 2:47
  • You already know how to reject!, so reject! the elements you don't want from the top-level array. Commented Dec 16, 2016 at 3:11
  • eqs.reject(&:empty?).each... Commented Dec 16, 2016 at 6:19

1 Answer 1

12

you can use Array#delete_if

arr = [{}, {}]
arr.delete_if &:empty?
# i.e. arr.delete_if { |hash| hash.empty? }
arr.empty?
# => true

Update

In Rails 6.1+ there is Array#compact_blank! as well

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.