Length and undefined method?

I have some code that reads a file. Each line has a number and a string.
I’m trying to test for the length of the string to be > 0 so blank lines
can be ignored.

file.each_line do |line|
line_items = line.split()
expense = line_items[1]
if expense.length < 1

The error I’m getting is:

undefined method `length’ for nil:NilClass (NoMethodError)

I’m obviosuly missing something, just not sure what. “expense” should
wind up a string so length should be a valid method.

Leam

if string is zero length then line_items[1] will be nil

"1 ".split
=> [“1”]

Have you considered what happens if there is a blank line in the file?

[1] pry(main)> line = " \n"
=> " \n"
[2] pry(main)> line_items = line.split
=> []

You might consider seeing if the split succeeded, for example

next if line_items.length < 2

Hope this helps,

Mike

The error I’m getting is:

undefined method `length’ for nil:NilClass (NoMethodError)

I’m obviosuly missing something, just not sure what. “expense” should wind up a
string so length should be a valid method.

Leam


http://31challenge.net
http://31challenge.net/insight

Mike S. [email protected]
http://www.stok.ca/~mike/

The “`Stok’ disclaimers” apply.

Subject: length and undefined method?
Date: Tue 30 Dec 14 08:27:30AM -0500

Quoting Leam H. ([email protected]):

The error I’m getting is:

undefined method `length’ for nil:NilClass (NoMethodError)

Umm… Most probably you should have

expense = line_items[0]

otherwise, if your original string (that you do not provide) does not
contain whitespace, line_items[1] will be nil.

Carlo

I think that was the issue; the loop hit the blank line before printing
anything.

What I would up doing was:

if line_items.count < 1

The almost depressing part was that the file contained expenditures and
tells me how much I’m spending on things like gas, books, etc. I
preferred blissful ignorance. :slight_smile:

Thanks!

Leam

On Tue, Dec 30, 2014 at 2:27 PM, Leam H. [email protected] wrote:

The error I’m getting is:

    undefined method `length' for nil:NilClass (NoMethodError)

I’m obviosuly missing something, just not sure what. “expense” should wind
up a string so length should be a valid method.

Split by default splits on whitespace. If your line doesn’t contain
whitespace or it contains only whitespace, or only one element which
is not whitespace, your line_items array will contain less than 2
elements:

2.0.0p195 :001 > “”.split
=> []
2.0.0p195 :002 > " “.split
=> []
2.0.0p195 :003 > " a”.split
=> [“a”]
2.0.0p195 :004 > " a ".split
=> [“a”]

So, at that point, line_items[1] will be nil:

2.0.0p195 :005 > " a ".split[1]
=> nil

so no length method there to be called. I suggest placing a
p line, line_items

to check what you really have.

Jesus.

1 Like