嗨,我有这样的哈希:
{"f8053d79-9ae8-4d78-888a-b866db12ce08"=>nil, "d1063ee8-1e22-4e8c-b5f5-76a4f8d3cdbe"=>"500"}
使用以下代码创建:
result = {}
source1.each {|k, v| result[k] = source2[k] if source2[k] != v }
当我尝试将此哈希存储在csv中时,出现以下错误:
no implicit conversion of nil into String (TypeError)
我希望用0替换nil应该可行。这是我目前的代码:
def relacenill(h)
h.each_with_object({}) { |(k,v),g|
g[k] = (Hash === v) ? relacenill(v) : v ? v : '0' }
end
但这似乎不起作用。你能帮忙吗?
答案 0 :(得分:2)
下面的代码将采用哈希值(假设x表示你的哈希值)并且如果它的任何值为nil将查找,将其设置为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
答案 1 :(得分:1)
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"}
答案 2 :(得分:0)
您的代码:
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
将其更改为:
CSV.open(filename, "w") {|csv| result.to_a.each {|elem| csv << elem} }
# => [["f8053d79-9ae8-4d78-888a-b866db12ce08", nil], ["d1063ee8-1e22-4e8c-b5f5-76a4f8d3cdbe", "500"]]
希望能解决它。
答案 3 :(得分:0)
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"
#=> }