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

这是一个示例.csv:file

这是我的代码:

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

在所有情况下,对于"rol"和"aseo",我什么也得不到,这种情况是行不通的.我肯定我错过了一些基本的东西.你能帮我吗?

推荐答案

哈希键是符号,但您使用字符串添加新键和进行查找.例如,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"

100

Ruby相关问答推荐

MongoDB通过Brew Services";未定义的方法`plist_starting';";

我可以在Ruby中以散列的形式访问方法的关键字参数吗?

有没有更好的方法来加入剩余不变的子列表?

VS Code Prettier 打破哈希访问

为什么我的二维 Ruby 数组的多个值会发生变化,尽管只更改了其中一个?

整数除以负数

如何从 url 获取文件扩展名?

在 gem 中放置/访问配置文件的位置?

Ruby 对象打印为指针

复制文件,在 Ruby 中根据需要创建目录

创建一个哈希值作为数组和默认值作为空数组

在 Ruby 中创建数字、字符串、数组或哈希的 md5 哈希

Ruby:继承与类变量一起工作的代码

将 Ruby 哈希转换为 YAML

Ruby 中方法名称的限制是什么?

STDERR.puts 与 Ruby 中的 puts 有何不同?

Ruby:更新哈希值的最简单方法是什么?

获取类中声明的所有实例变量

如何转换 Ruby 哈希,使其所有键都是符号?

在 Ruby 中使用元组?