Ruby: Why is there a `nil` at the end of all the s

2019-08-23 14:25发布

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

... which means that each array position in record apparently has data of type String and of type nil. why is this?

1条回答
ゆ 、 Hurt°
2楼-- · 2019-08-23 15:10

Your database_array has more dimensions than you think.

Your end-of-stanza marker, |--|--|...|--| has a newline after it. So, file_as_string returns something like this:

"26188\nWHL...|--|--|\n"

and is then split() on end-of-stanza into something like this:

["26188\nWHL...1160 RPM\n", "\n"]  # <---- Note the last element here!

You then split each again, but "\n".split("\n") gives an empty array, the first element of which comes back as nil.

查看更多
登录 后发表回答