ruby - 已经初始化的常量警告

标签 ruby warnings

我正在使用 Nokogiri 代码在 HTML 节点之间提取文本,当我读入文件列表时出现这些错误。我没有使用简单的嵌入式 HTML 得到错误。我想消除或抑制警告但不知道如何。警告出现在每个 block 的末尾:

extract.rb:18: warning: already initialized constant EXTRACT_RANGES
extract.rb:25: warning: already initialized constant DELIMITER_TAGS

这是我的代码:

#!/usr/bin/env ruby -wKU
require 'rubygems'
require 'nokogiri'
require 'fileutils'

source = File.open('/documents.txt')
source.readlines.each do |line|
  line.strip!
  if File.exists? line
    file = File.open(line)

doc = Nokogiri::HTML(File.read(line))

# suggested by dan healy, stackoverflow 
# Specify the range between delimiter tags that you want to extract
# triple dot is used to exclude the end point
# 1...2 means 1 and not 2
EXTRACT_RANGES = [
  1...2
 ]

# Tags which count as delimiters, not to be extracted
DELIMITER_TAGS = [
  "h1",
  "h2",
  "h3"
]

extracted_text = []

i = 0
# Change /"html"/"body" to the correct path of the tag which contains this list
(doc/"html"/"body").children.each do |el|

  if (DELIMITER_TAGS.include? el.name)
    i += 1
  else
    extract = false
    EXTRACT_RANGES.each do |cur_range|
      if (cur_range.include? i)
        extract = true
        break
      end
    end

    if extract
      s = el.inner_text.strip
      unless s.empty?
        extracted_text << el.inner_text.strip
      end
    end
  end
end

print("\n")
puts line
print(",\n")
# Print out extracted text (each element's inner text is separated by newlines)
puts extracted_text.join("\n\n")
  end
end

最佳答案

如果代码缩进得当,就会更容易注意到常量定义是在一个循环中完成的。

比较

source.readlines.each do |line|
  # code
  if true

# Wrongly indented code

# More
# Wrongly
# Indented
# Code
EXTRACT_RANGES = [
  1...2
 ]

# Several more pages of code
  end
end

source.readlines.each do |line|
  # code
  if true

    # Correctly indented code

    # What is a constant doing being defined
    # this far indented?
    # Oh no - it's in a loop!

    EXTRACT_RANGES = [
      1...2
    ]

    # Several more pages of code
  end
end

关于ruby - 已经初始化的常量警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7849410/

相关文章:

ruby - 使用ARGV创建目录( ruby )

gcc - 如何在 GCC 中隐藏 "defined but not used"警告?

ruby-on-rails - ruby Tmail 错误 : undefined symbol: rb_get_kcode

sql - SQL 查询的最大长度

ruby - 将基于字符串的分钟和秒值相加

file-upload - 在上传之前警告用户文件太大

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c++ 位域和-Wconversion

c++ - 未知来源的警告 : "can' t find linker symbol for virtual table for. .."

Ruby/Cucumber/Capybara 测试多部分文件上传