Comparing 2 Time objects breaks compiler with "Nil"

hello, trying to compare to Time objects, but compiler keeps erroring out on Nil

if host.services.not_nil!
  host.services.each do |svc|
     if svc.updated_at
            Log.warn {svc.updated_at}
            Log.warn { typeof(svc.updated_at)}
            diff = Time.utc - svc.updated_at
      end
  end
end

my database object svc.updated_at is a (Time | Nil)
Im adding an existence check, with “if svc.updated at”

compiler fails to compile with

 21 | diff = Time.utc - svc.updated_at
                                  ^---------
Error: expected argument #1 to 'Time#-' to be Time, not (Time | Nil)

also tried

if svc.updated_at.not_nil!

but same error

Basically see if var - Crystal.

You’ll prob want to do something like:

if updated_at = svc.updated_at
  diff = Time.utc - updated_at
end

thanks, I added a .try and seems to work

 svc.updated_at.try do |updated_at|
            Log.warn {updated_at}
            Log.warn { typeof(updated_at)}
            diff = Time.utc - updated_at
            Log.info {diff}
          end

:+1:, same end result yea. Depending on your use case, I’d prob also take a minute and read thru Measuring Time.

Code like following is too too too bad

if host.services.not_nil!

You really should read document before write more code.

better than previous example, but still too bad.

 svc.updated_at.try do |updated_at|
            diff = Time.utc - updated_at
          end

You really should use a if for both case, but, not_nil! not not designed for used together with if.