# Ruby: TypeError: nil can't be coerced into Integer / String can't be coerced into Integer

**Code:** `TypeError: nil can't be coerced into Integer` · **Category:** Ruby / Rails · **Seen on:** Ruby

Arithmetic combined a number with `nil` (or a String) which Ruby can't convert automatically.

## Meaning

A variable or column used in `+`, `*`, `sum` is nil. Default values (`to_i`, `|| 0`, `.to_f`), DB defaults (`null: false, default: 0`), and parsing params (`Integer(params[:n], exception: false)`) fix it. `"5" + 1` gives "no implicit conversion", while `1 + "5"` gives "String can't be coerced".

## Common causes

- nil attribute used in arithmetic
- String from params not converted
- `sum` over nil elements
- Missing DB default
- Operand order (`1 + nil`)

## Quick fix

1. `(value
2. 0) + 1` or `value.to_i`
3. Add DB defaults and `null: false`
4. `compact.sum` for arrays with nil

## Detailed fix by platform

### Ruby

1. `total = items.map { |i| i.price.to_f }.sum`

## How to diagnose

1. **Operand** — Which is nil?
2. **Source** — Param/DB?
3. **Default** — Provided?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/ruby/typeerror-nil-cant-be-coerced-into-integer)
