Tuesday, January 29, 2013

Refactoring "if nil?"

Very often we have checking against nil value like this:

if products.nil?
  products.first.total_amount
else
  0.0
end


There is a cleaner way to achieve the same result:

products.first.try(:total_amount) || 0.0

1 comment:

  1. I think the source code is:
    ```
    if products.first.present?
    products.first.total_amount
    else
    0.0
    end
    ```

    Or the second statement does not match at all

    Unless you mean `products.try(:first).try(:total_amount) || 0.0`
    But the first code is still wrong :O

    ReplyDelete