Quick Answer

Handle type conversion issues.

Understanding the Issue

Occurs when Ruby cannot automatically convert between types, often in string/number operations or method arguments.

The Problem

This code demonstrates the issue:

Ruby Error
"5" + 3 # TypeError

The Solution

Here's the corrected code:

Ruby Fixed
# Solution 1: Explicit conversion
"5" + 3.to_s # => "53"
5 + "3".to_i # => 8

# Solution 2: Duck typing
def add(a, b)
  if a.respond_to?(:to_i) && b.respond_to?(:to_i)
    a.to_i + b.to_i
  else
    raise TypeError, "Cannot convert to numbers"
  end
end

# Solution 3: Type checking
def process(input)
  raise ArgumentError unless input.is_a?(String)
  # ...
end

Key Takeaways

Explicitly convert types when needed and validate inputs.