Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove nil values from hash

Tags:

json

ruby

hash

I am looking to remove keys from hash that have nil value. article is a class storing each article, and attributes method stores the article as hash.

Expected Result:

{"articles":[{"results":[{"author":null,"title":"Former bar manager jailed for preying on homeless 14-year-old girl","summary":"<p><img src=\"http://images.theage.com.au/2015/08/24/6790912/Thumbnail999662740gisd08image.related.thumbnail.320x214.gj68pg.png1440386418031.jpg-90x60.jpg\" width=\"90\" height=\"60\" style=\"float:left;margin:4px;border:0px\"/></p>A man who preyed on a 14-year-old girl he came across living on the streets of&#160;Wodonga has been jailed for nine months.","images":null,"source":null,"date":"Mon, 24 Aug 2015 03:20:21 +0000","guid":"<guid isPermaLink=\"false\">gj68pg</guid>","link":"http://www.theage.com.au/victoria/former-bar-manager-jailed-for-preying-on-homeless-14yearold-girl-20150824-gj68pg.html","section":null,"item_type":null,"updated_date":null,"created_date":null,"material_type_facet":null,"abstract":null,"byline":null,"kicker":null}]}]}

Looking to remove null values from the above output.

def attributes
  hash = {
    "author" => @author,
    "title" => @title,
    "summary" => @summary,
    "images" => @images,
    "source" => @source,
    "date" => @date
  }
  hash = {}
  count = 0
  article.attributes.each do |key,value|
    if value == nil
      hash[count] = article.attributes.delete(key)
      count += 1
    end
  end
  hash.to_json

The result is as below:

{"0":null,"1":null,"2":null,"3":null,"4":null,"5":null,"6":null,"7":null,"8":null,"9":null,"10":null}
like image 302
coder05 Avatar asked Nov 27 '22 04:11

coder05


1 Answers

If you're on Ruby >= 2.4.6, you can use compact.

https://apidock.com/ruby/v2_4_6/Hash/compact

Example:

hash = {:foo => nil, :bar => "bar"}
=> {:foo=>nil, :bar=>"bar"}
hash.compact
=> {:bar=>"bar"}
hash
=> {:foo=>nil, :bar=>"bar"}

There's also compact! which removes nil values, or nil if no values in the hash were nil (from version >= 2.5.5).

https://apidock.com/ruby/v2_4_6/Hash/compact%21

Example:

hash
=> {:foo=>nil, :bar=>"bar"}
hash.compact!
=> {:bar=>"bar"}
hash
=> {:bar=>"bar"}
hash.compact!
=> nil
like image 160
MattD Avatar answered Nov 29 '22 19:11

MattD