0

i am stuck in weird issue while comparing dates in ruby on rails.

here is what i am trying to do. i have parsed a file and selected a date into a variable @timeinFile. i am comparing this value to created_at of my User. here is the code:

@date=User.last.created_at
@arr.each do |i| 
    j=i.partition('(')[2]  
    @timeinFile=j.partition(')')[0].to_datetime
    if @date < @timeinFile    #Error: undefined method `to_datetime' for nil:NilClass
            @val='true'
    end
end

when i Comment if statement and paste values individually i get the following output

<p> <%= @date %> </p> ----------> 2013-08-05 09:16:33 UTC 

<p><%= @timeinFile.to_time %></p> -------------> 2012-10-02 12:00:00 UTC

anyone plz tell me what wrong i have done.

Edit

<a href="http://www.cpsc.gov/en/Recalls/2013/Fitness-Anywhere-Recalls-Early-Model-Suspension-Trainer-Devices-Due-to-Fall-Hazard/" target="_blank">Fitness Anywhere Recalls Early Model Suspension Trainer Devices Due to Fall Hazard</a> (Tue, 02 Oct 2012 12:00:00 GMT) Fitness Anywhere has received 570 reports of the strap length adjustment buckles breaking with 13 reports of injuries. TRX suspension trainers sold from 2006 through 2009. </p> </body> </html> 

this is the line i am getting in @arr. next step was to partition with ( and then with ) to get date in round brackets...

7
  • Are you sure the error points to line with comparison? Commented Aug 27, 2013 at 7:47
  • 1
    It would be useful to see the contents of @arr when you get the error. Commented Aug 27, 2013 at 7:48
  • @MarekLipka yep it points to the same line :( Commented Aug 27, 2013 at 7:49
  • @arr.compact.each can you please try this i think in @arr contains some nil values Commented Aug 27, 2013 at 7:54
  • @NeilSlater check the edit i made to original post. i am getting error on the statement i have pasted Commented Aug 27, 2013 at 7:59

1 Answer 1

3

Well, why do you use @timeinFile in your code and @timeonsite in your tests?

#Error: undefined method `to_datetime' for nil:NilClass

basically means you are calling a method on a nil object, and I feel the error is triggered on the line BEFORE the if statement.

What happens when you put this check?

unless j.partition(')')[0].nil?
  @timeinFile=j.partition(')')[0].to_datetime
else
  @timeinFile = DateTime.now
end

If it doesn't give you an error you can go and find out why that value is nil.

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, thanks for the editing @Mischa, this morning my typing is quite wobbly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.