簡體   English   中英

Rails-升級到ruby 2.2.2-沒有將數組隱式轉換為String(TypeError)

[英]Rails- upgrading to ruby 2.2.2 - no implicit conversion of Array into String (TypeError)

我一直在研究一個項目,該項目只是讀取文件並將其解析以存儲到數據庫中。 項目運行正常,但是在更新ruby 2.2.2之后運行代碼,我收到了以前沒有的錯誤:

in `foreach': no implicit conversion of Array into String (TypeError)

這是導致錯誤的foreach的代碼段:(讓我知道是否需要更多代碼)。

def parse(file_name)
  File.foreach(file_name).with_index do |line, line_num|
    puts "\nLine #{line_num}: #{line}"

有人知道發生了什么嗎? 謝謝

編輯:抱歉,這是一個片段! 我將此紅寶石代碼稱為“ parse_log_file_test”,稱為“ parse_log_file_test”

require File.dirname(__FILE__) + '/../test_helper'

class ParseLogFileTest < ActiveSupport::TestCase

  filename = Array.new

  Dir.glob('database/oag-logs/*.log').each do |log_file|

    filename.push(log_file)

  end

  parser = ParseLogFile.new

  parser.parse(filename)

  test 'parse' do
    parser = ParseLogFile.new

    filename.each do |log_file|

      begin

        parser.parse(log_file)
      rescue

        puts"ERROR: Unable to parse line #{log_file}"

      end
    end
    assert true
  end
end

我猜想您省略了函數的end ,但是如果您沒有它,那就需要它。

此錯誤表明傳遞給file_name進行parse的參數是數組而不是字符串。

但是,在這種情況下,它在Ruby 1.8.4上失敗了:

File.foreach([]).with_index do |line, line_num|
  puts "\nLine #{line_num}: #{line}"
end

輸出:

TypeError: can't convert Array into String
    from (irb):1:in `foreach'
    from (irb):1:in `with_index'
    from (irb):1
    from :0

因此,我的猜測是,生成傳遞給您的值以進行parse的代碼在您先前的Ruby版本中返回了一個字符串,並在2.2.2中返回了一個數組。

在您的情況下,該錯誤是由parser.parse(...)test 'parse' do行上方parser.parse(...)的第一次調用引起的,而不是由test方法內部的調用引起的。 我猜您是在遷移后將調用放在那兒,可能是為了調試問題。 但是,您傳遞給第一個調用的參數與傳遞給測試方法內部的調用的參數不同,因此,失敗的原因與測試方法中的調用原因不同。

要查看測試內部導致的錯誤,只需刪除以下行

      rescue

        puts"ERROR: Unable to parse line #{log_file}"

(保留end否則您也必須刪除begin 。)

這樣,錯誤將命中測試運行器,該運行器通常會顯示該錯誤,包括消息和堆棧跟蹤。

同意上面的海報,您很可能會丟失引號。 但是,它與2.2.2無關,可能這次您復制文件名的方式有所不同。

因此,顯然,這是在Windows上升級到ruby 2.2.2的問題。 經過這個錯誤后,我只遇到了更多的錯誤.. nokogiri..etc

我最近有一台Mac,錯誤消失了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM