Improperly exiting loop with DATA and __END__

I have this bit of code that loops through the END data and does
some time sheet processing. All that bit works, but when I get to the
end of the “DATA” I get an error about calling split for a
nil:NilClass…I an sure it is because I am trying to process the last
record which is an empty string. I’ve been googling and looking at the
book for hours, but can not get this bit right. How do I trap the empty
string and exit the loop properly. Thanks in advance for any help!

Friday – Morning hours 4.75 Afternoon 5.23 total 9.98

hour_calu.rb:12: private method `split’ called for nil:NilClass

(NoMethodError)

Exit code: 1

while times = DATA.gets.chomp.split(",")

  day_of_week = times[0].split(",")

##bunch of other rubish calculations go here

printf(" %8s -- Morning hours %01.2f  day_of_week, morning_e_time)
 week_total =+ morning_e_time + afternoon_e_time

end

puts
##printf(“Weekly total %01.2f\n”,week_total)

END
Monday,07:46,12:04,12:45,17:09
Tuesday,08:00,12:28,13:21,18:09
Wednesday,07:49,12:05,12:58,18:01

Friday – Morning hours 4.75 Afternnon 5.23 total 9.98
hour_calu.rb:12: private method `split’ called for nil:NilClass
(NoMethodError)

Exit code: 1

Robert K. wrote:

while times = DATA.gets.chomp.split(",")

May I link to this thread in a possible RCR for a -> operator (which
would solve the problem by doing:
while times = DATA.gets->chomp.split(","))?

A solution that works in current ruby:
while times = DATA.gets
times = times.chomp.split(",")

Regards
Stefan

DATA.readlines.each{ |line|
times = line.chomp.split(",")
unless times.empty?
#do stuff here
p times
end
}
#=> [“Monday”, “07:46”, “12:04”, “12:45”, “17:09”]
#=> [“Tuesday”, “08:00”, “12:28”, “13:21”, “18:09”]
#=> [“Wednesday”, “07:49”, “12:05”, “12:58”, “18:01”]

END
Monday,07:46,12:04,12:45,17:09
Tuesday,08:00,12:28,13:21,18:09
Wednesday,07:49,12:05,12:58,18:01

Robert K. wrote:

I have this bit of code that loops through the END data and does
some time sheet processing. All that bit works, but when I get to the
end of the “DATA” I get an error about calling split for a
nil:NilClass…I an sure it is because I am trying to process the last
record which is an empty string.

Not quite. After the last line of the file has been read, if you call
gets() again, it returns nil. If your last line was really a blank
line, you wouldn’t get an error:

line = “”
processed_line = line.chomp.split(",")
puts “—>#{processed_line}<----”

output:
—><----

On 27.10.2007 01:00, Phrogz wrote:

END
Monday,07:46,12:04,12:45,17:09
Tuesday,08:00,12:28,13:21,18:09
Wednesday,07:49,12:05,12:58,18:01

I believe it’s more efficient if you omit the “.readlines”.

Kind regards

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs