Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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

like image 623
DktPhl2018 Avatar asked Dec 13 '22 11:12

DktPhl2018


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.

like image 183
Aleksei Matiushkin Avatar answered Feb 23 '23 10:02

Aleksei Matiushkin


you need to convert the variable num into string

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

refer the official docs https://www.rubyguides.com/2018/09/ruby-conversion-methods/

like image 20
syam lal Avatar answered Feb 23 '23 10:02

syam lal