ruby code error: '+'no implicit conversion of Integer into String

Viewed 10562

Getting runtime code error: In '+': no implicit conversion of Integer into String TypeError

num = 5;
puts ("this is number: " + num);

Actual Result:

runtime code error: In '+': no implicit conversion of Integer into String TypeError

Expected Result - I should see printed statement -

this is number: 5

2 Answers

Don’t put spaces between method names and opening parentheses in the first place.

The cause of the error one cannot add numbers to strings, ruby prevents implicit coercion. One might use string interpolation:

puts "this is number: #{num}"

or convert the number to string explicitly:

puts("this is number: " + num.to_s)

Sidenote: semicolon at the end of the line is redundant and should be avoided.

Related