BB123 BB123 - 6 months ago 3x
Ruby Question

Getting error only some of the time when calculating: "Undefined method '/' for nil:NilClass"

I'm using Ruby on Rails and am iterating through an object.

I want to display a percentage from dividing two columns' value then multiplying by 100.

I don't know if I can just write it in the view or if I need to write a method in the model or controller. I first chose to write it in the view and am getting an error "Undefined method "/" for nil:NilClass" only some of the time.

I think that's an error that's thrown when there is no value for one of the columns. When I write the method in the model or controller, there is no error but the value I'm trying to display is blank.

Here's how my calculation looks in the view:


<%= number_to_percentage(object.column1 / object.column2.round(2) * 100, precision: 0) %>


/ is a method like any other in Ruby and a / b is just a different way of saying a./(b) so that error is telling you that object.column1 is nil.

You have to decide what you want object.column1.nil to mean:

  • Do you display such things specially? If so then:

    <% if object.column1.nil? %>
      nil or whatever else you want to say
    <% else %>
      <%= object.column1 / object.column2.round(2) * 100, precision: 0) %>
    <% end %>
  • Do you want to treat nil like zero? If so then:

    <%= object.column1.to_i / object.column2.round(2) * 100, precision: 0) %>

    You'd want to use to_f instead of to_i if the column1 is a floating point value. If n is an integer then n.to_i == n but nil.to_i == 0 so to_i is a convenient way to hide the common "treat nil as 0" logic; similarly for floating_point_value.to_f and nil.to_f.

If object.column2 can also be nil then you have to make similar decisions about how to handle object.column2.nil?.