Ruby: remove empty curly braces in a hash array

The content I'm scraping contains some empty elements. I either have to stop the variables that are set if there is no data (preferable), or just perform some operation after that and completely remove the hashes containing spaces.

Here is 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 them are empty, and I do not know what in advance. So I tried to iterate over the array and remove the empty values ​​with:

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

This successfully removes empty keys and values, but I still have empty curly braces ...

Conclusion:

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

I want to completely get rid of empty hashes! Does anyone know what I'm doing here?

+4
source share
1

Array # delete_if

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

Source: https://habr.com/ru/post/1663903/


All Articles