ハッシュから nil 値を削除する
概要
ハッシュから値が nil のキーを削除しようとしています。 Article は各記事を格納するクラスで、Attributes メソッドは記事をハッシュとして格納します。
期待される結果:
{"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 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}]}]}
上記の出力から null 値を削除しようとしています。
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
結果は以下の通りです。
{"0":null,"1":null,"2":null,"3":null,"4":null,"5":null,"6":null,"7":null,"8":null,"9":null,"10":null}
解決策
コンパクトにお使いいただけます。
https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://ruby-doc.org/core-2.7.0/Hash.html#method-i-compact
例:
hash = {:foo => nil, :bar => "bar"}
=> {:foo=>nil, :bar=>"bar"}
hash.compact
=> {:bar=>"bar"}
hash
=> {:foo=>nil, :bar=>"bar"}
コンパクトもあります!これは nil 値を削除するか、ハッシュ内の値が nil でない場合は nil を返します。
https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://ruby-doc.org/core-2.7.0/Hash.html#method-i-compact-21
例:
hash
=> {:foo=>nil, :bar=>"bar"}
hash.compact!
=> {:bar=>"bar"}
hash
=> {:bar=>"bar"}
hash.compact!
=> nil