简体   繁体   中英

Replacing nil in hash with 0 and place in a csv

Hi I have a hash something like this:

{"f8053d79-9ae8-4d78-888a-b866db12ce08"=>nil, "d1063ee8-1e22-4e8c-b5f5-76a4f8d3cdbe"=>"500"}

which was created using the below code:

result = {}
source1.each {|k, v| result[k] = source2[k] if source2[k] != v }

When I try to store this hash in a csv, I get the following error:

no implicit conversion of nil into String (TypeError)

I'm hoping replacing nil with 0 should work. This is the current code I have:

def relacenill(h)
  h.each_with_object({}) { |(k,v),g|
    g[k] = (Hash === v) ?  relacenill(v) : v ? v : '0' }
end

But this doesn't seem to be working. Can you please help?

below code will take the hash (let's say x is your hash) and will look up if any of its values is nil, will set it to 0

2.3.1 :001 > x = {:a => 5, :b => nil} 
2.3.1 :002 > x.each {|k,v| x[k] = x[k].nil? ? 0 : x[k] }
=> {:a=>5, :b=>0} 


2.3.1 :009 > require 'csv'
 => true 
2.3.1 :010 > x
 => {:a=>5, :b=>0} 
2.3.1 :011 > CSV.open('lorem.csv', 'wb') {|csv| x.to_a.each {|e| csv << e}}
 => [[:a, 5], [:b, 0]] 
2.3.1 :012 > exit
$ cat lorem.csv 
a,5
b,0
hash = {"f8053d79-9ae8-4d78-888a-b866db12ce08"=>nil, "d1063ee8-1e22-4e8c-b5f5-76a4f8d3cdbe"=>"500"}

hash = hash.reduce({}) do |acc, object| 
    acc[object.first] = object.last.nil? ? '0' : object.last
    acc
  end
# => {"f8053d79-9ae8-4d78-888a-b866db12ce08"=>"0", "d1063ee8-1e22-4e8c-b5f5-76a4f8d3cdbe"=>"500"}

Your code:

CSV.open(filename, "w") {|csv| result.to_a.each {|elem| csv << elem.to_s} }

# => undefined method `map' for "[\"f8053d79-9ae8-4d78-888a-b866db12ce08\", nil]":String

Change it to:

CSV.open(filename, "w") {|csv| result.to_a.each {|elem| csv << elem} }

# => [["f8053d79-9ae8-4d78-888a-b866db12ce08", nil], ["d1063ee8-1e22-4e8c-b5f5-76a4f8d3cdbe", "500"]]

Hope that solved it.

data = {
  "f8053d79-9ae8-4d78-888a-b866db12ce08" => nil, 
  "d1063ee8-1e22-4e8c-b5f5-76a4f8d3cdbe" => "500"
}

data_without_nils = data.each_with_object({}){ |(k, v), h| h[k] = v || '0' }
#=> {
#=>   "f8053d79-9ae8-4d78-888a-b866db12ce08" => "0", 
#=>   "d1063ee8-1e22-4e8c-b5f5-76a4f8d3cdbe"=>"500"
#=> }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM