Float64, a Hash, and Nil

How to get out of this bit of trouble? I have:

best_so_far = { "dems" => nil, "solver" => nil, "cost" => 9999999.9 } 

and later on I have, where cost is a Float64:

if cost < best_so_far["cost"]

The ‘if’ statement is tripping up the compiler. It complains
Error: no overload matches ‘Float64#<’ with type (Float64 | Nil)

You can do:

if (temp = best_so_far["cost"]) && cost < temp


if cost < best_so_far["cost"].not_nil!

If you know the “cost” key is not nil you can do if cost < best_so_far["cost"].not_nil!.

Depends on what you are trying to do, Hash might not be the best type to use here. Maybe a class with explicitly named properties might be better, something like:

class BestSoFar
  property dems : NoIdeaWhatTypeYouWant? = nil
  property solver : NoIdeaWhatTypeYouWant? = nil
  property cost = 9999999.9
1 Like

The class BestSoFar looks much better! That is how I’m doing it now. BTW, it’s a combinatorial optimizer I’m working on.

What the heck was I thinking? Why didn’t I think of that in the first place? Probably was doing too much Javascript the last few days.