I created a function that compares two hashes and returns a report on whether the subtraction of their values is negative or not.
The problem comes down to having a cost hash for a building and a current resources hash like:
cost = {:wood => 300, :stone => 200, :gold => 100}
reqs = {:wood => 200, :stone => 220, :gold => 90}
This one should return a report hash like:
report = { :has_resources => false, :has_wood => true, :has_stone => false, :has_gold => true }
Now, in the cost hash, :gold, :stone or :wood can be nil, i.e. non-existent.
My first attempt is definitely not the Ruby way and I don't like the function. It works, but I want to find a way to write it in a better manner:
def has_resources?(cost)
report = { :has_resources => true, :has_wood => true, :has_stone => true, :has_gold => true }
if not cost[:wood].nil?
if self.wood < cost[:wood]
report[:has_wood] = false
report[:has_resources] = false
end
end
if not cost[:stone].nil?
if self.stone < cost[:stone]
report[:has_stone] = false
report[:has_resources] = false
end
end
if not cost[:gold].nil?
if self.gold < cost[:gold]
report[:has_gold] = false
report[:has_resources] = false
end
end
end
How should I rewrite this? I don't like the .nil? checks here, but I have to include them since the < operator does not work on nil objects. I also don't like having so many ifs.