Ruby:为什么数组中所有字符串的末尾都有一个“ nil”? [英] Ruby: Why is there a `nil` at the end of all the strings in my array?
问题描述
因此,我用Ruby编写了一些代码,将文本文件分成几行,然后根据分隔符将这些行分组。然后将此输出写入数组,该数组将传递给方法,该方法将HTML吐出到文本文件中。当我尝试以不同的方法使用gsub替换HTML文本文件中的占位符时,出现了问题,这些值来自 record
数组-Ruby一直告诉我我正在传递以零值表示。在尝试调试程序的该部分几个小时后,我决定将目光转向其他地方,我认为自己正在做些事情。该程序的修改版本发布在下面。
So I've written some code in Ruby to split a text file up into individual lines, then to group those lines based on a delimiter character. This output is then written to an array, which is passed to a method, which spits out HTML into a text file. I started running into problems when I tried to use gsub in different methods to replace placeholders in a HTML text file with values from the record
array - Ruby kept telling me that I was passing in nil values. After trying to debug that part of the program for several hours, I decided to look elsewhere, and I think I'm on to something. A modified version of the program is posted below.
以下是输入文本文件的示例:
Here is a sample of the input text file:
26188
WHL
1
Delco
B-7101
A-63
208-220/440
3
285 w/o pallet
1495.00
C:/img_converted/26188B.jpg
EDM Machine Part 2 of 3
AC Motor, 3/4 Hp, Frame 182, 1160 RPM
|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|
这是我一直在测试的代码的一个片段:
Here is a snippet of the code that I've been testing with:
# function to import file as a string
def file_as_string(filename)
data = ''
f = File.open(filename, "r")
f.each_line do |line|
data += line
end
return data
end
Dir.glob("single_listing.jma") do |filename|
content = file_as_string(filename)
content = content.gsub(/\t/, "\n")
database_array = Array.new
database_array = content.split("|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|")
for i in database_array do
record = Array.new
record = i.split("\n")
puts record[0]
puts record[0].class end
end
运行该代码后,我得到此输出:
When that code is run, I get this output:
john@starfire:~/code/ruby/idealm_db_parser$ ruby putsarray.rb
26188
String
nil
NilClass
...这意味着每个数组记录
中的位置显然具有类型为 String
和类型为无
。为什么?
... which means that each array position in record
apparently has data of type String
and of type nil
. why is this?
推荐答案
您的 database_array
具有比您想象的更多的维度。
Your database_array
has more dimensions than you think.
您的节结尾标记 |-| ----...... |-|
之后有换行符。因此, file_as_string
返回如下内容:
Your end-of-stanza marker, |--|--|...|--|
has a newline after it. So, file_as_string
returns something like this:
"26188\nWHL...|--|--|\n"
然后是 split()
在节末变成这样:
and is then split()
on end-of-stanza into something like this:
["26188\nWHL...1160 RPM\n", "\n"] # <---- Note the last element here!
然后您又将它们分开,但 \n .split( \n)
给出一个空数组,其第一个元素返回为 nil
。
You then split each again, but "\n".split("\n")
gives an empty array, the first element of which comes back as nil
.
这篇关于Ruby:为什么数组中所有字符串的末尾都有一个“ nil”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!