如何在ruby中使用csv转换器编码?

问题描述 投票:0回答:1
require 'csv'
module Expertus
 class Dataset < Array
  attr_accessor :data_type, :udc_id, :filename_suffix

# knows its common_udc_id and data type

  def initialize *args
    CSV::Converters[:non_octal_integer] = lambda { |f|
     begin
      e = f.encode(CSV::ConverterEncoding)
      unless e == "0"
        if e.starts_with? "0"
          return f
        end
      end
    rescue
      return f
    end
    Integer(f.encode(CSV::ConverterEncoding)) rescue f
  }

  CSV::Converters[:non_octal_float] = lambda { |f|
    begin
      e = f.encode(CSV::ConverterEncoding)
      unless e.starts_with? "0."
        if e.starts_with? "0"
          return f
        end
      end
    rescue
      return f
    end
    Float(f.encode(CSV::ConverterEncoding)) rescue f
  }

  CSV::Converters[:string_to_bool] =->(f) {
    ['true', 'false'].include?(f) ? f=='true' : f
  }
  @csv_options = {:converters => [:non_octal_integer, :non_octal_float, :string_to_bool]}
  @data_type = nil
  @udc_id = nil
  @filename_suffix = nil
  super
end
def expected_output_filename
    return "#{@udc_id}_#{@data_type}#{@filename_suffix}.csv"
end
def read_expected_output_file_from_directory! directory
  if directory.is_a? String
    p "Directory/File:::: #{File.join(directory, self.expected_output_filename)}"
    p "@csv_options::: #{@csv_options}"
    csv_data = CSV.read File.join(directory, self.expected_output_filename), @csv_options
  else
    csv_data = CSV.new(directory, @csv_options).read
  end
  csv_data[0].map! { |h| h.to_sym }
  self.clear
  self.replace csv_data
end

我在 jRuby 脚本中调用 read_expected_output_file_from_directory 方法,如下所示:

expected_dataset.read_expected_output_file_from_directory! File.join($session.script_dir, '..', 'expectedresults')

它抛出一个错误:

[“参数数量错误(给定 2 个,预期 1 个)(ArgumentError)”]

/home/eip/jruby-9.4.5.0/lib/ruby/stdlib/csv.rb:1821:在“读”中

有任何帮助吗?谢谢

ruby upgrade jruby
1个回答
0
投票

正如 Stefan 在上面的评论中指出的

CSV.read
CSV.new
期望选项作为 关键字参数传递。

您可以通过 ** 将哈希值转换为关键字参数

,例如:

CSV.new(directory, **@csv_options)
    
© www.soinside.com 2019 - 2024. All rights reserved.