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.
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.
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: