Reputation: 796
In my view helper method, I want to be able to calculate the range between two numbers. Right now I am doing this:
def show_range
max = @shirts.get_max
min = @shirts.get_min
max-min
end
I know that max and min are working because I can just print each of their values out. However, when I try to do this simply math function in my "module ShirtsHelper", I get the following error:
undefined method `-' for nil:NilClass
Why am I getting this error and what can I do to fix it?
Upvotes: 0
Views: 837
Reputation: 10856
You get the error because your max
variable is nil
and there is no matching method -
on nil
. You could check whether min and max are not nil
with max - min if max && min
. However, I guess you might want to provide a fallback value (e.g. 0) in this case, so you might be looking for something like this
def show_range
max = @shirts.get_max
min = @shirts.get_min
if max && min
max - min
else
0 # Fallback value
end
end
Or even more concise:
def show_range
max = @shirts.get_max
min = @shirts.get_min
max && min ? max - min : 0
end
Upvotes: 3