Hash[key]在Ruby中返回nil,但是Hash没有nil值



我正在用.csv文件填充数据库,其中每一行都是长代码。我有一个包含每列位置的散列,然后创建另一个散列,将列名存储为键和值。此外,我想基于de csv中的列创建一些其他列,但当尝试调用de values来执行操作时,它们返回nil。然而,当我调用散列时,它显示没有一个值是nil。

下面是。csv:文件

的示例下面是我的代码:
require 'rake'
require 'csv'
namespace :import do
desc "delete old data and load data from file"
task  rolcobro: :environment do
SiiPropiedad.delete_all
filename = ENV["FILE"].present? ? ENV["FILE"] : "sample.txt"

rowshash = {codigo_comuna: [0,4],
anio: [5,8],
semestre: [9,9],
aseo: [10,10],
direccion: [17,56],
manzana: [57,61],
predio: [62,66],
serie: [67,67],
cuota_trimestral: [68,80],
avaluo_total: [81,95],
avaluo_exento: [96,110],
anio_fin_exencion: [111,114],
ubicacion: [115,115],
destino: [116,117]
}
dir = "db/csv/"
filepath = File.join Rails.root, "#{dir}#{filename}"
CSV.foreach(filepath, headers: false) do |row|
texto = row[0].to_s
attributes = {"texto": texto}
rowshash.each do |key,value|
attributes[key] = texto[value[0]..value[1]]
end

#HERE THE "rol" MUST BE CREATED FROM "manzana" AND "predio". EX: IF attributes["manzana"] = "00308" AND attributes["predio"] = "00061" (AS STR) THEN attributes["rol"] should be "308-61"
attributes["rol"] = "#{attributes["manzana"].to_i}-#{attributes["predio"].to_i}"
#HERE IF IT IS " " I WANT THE FIRST MSG, ELSE (WHEN IT IS "A") THE LATER
attributes["aseo"] == " " ? "Cuota trimestral no incluye aseo" : "Cuota trimestral incluye aseo"
SiiPropiedad.find_or_create_by(attributes)
end
end
end

在所有情况下,我都没有得到"而对于"aso"&;这种情况行不通。我肯定我漏掉了一些基本的东西。你能帮我一下吗?

您的散列键是符号,但是您使用字符串来添加新键和查找。例如,attributes["rol"] = "value"将生成一个字符串键"rol"

rowshash = {
symbol:            "this is a symbol",
"also symbol":     "symbol again",
:"third symbol" => "another symbol",
"string"        => "a string key"
}
rowshash[:symbol]         # => "this is a symbol"
rowshash[:"also symbol"]  # => "symbol again"
rowshash[:"third symbol"] # => "another symbol"
rowshash["string"]        # => "a string key"

不能用字符串查找符号键,反之亦然。当你请求一个不存在的键时,你得到的默认值是nil:

rowshash["symbol"]        # => nil
rowshash["also symbol"]   # => nil
rowshash["third symbol"]  # => nil
rowshash[:"string"]       # => nil

如果您想获得一个不同的默认值,您可以对哈希本身使用default=方法。

rowshash.default = "new default"
rowshash["not found"]     # => "new default"

https://rubyapi.org/3.1/o/hash

相关内容

  • 没有找到相关文章

最新更新