Steven Aguilar Steven Aguilar - 2 months ago 18
Ruby Question

in `+': String can't be coerced into Fixnum (TypeError)

Currently working on a HackerRank problem in Ruby. When I try to compile


in `+': String can't be coerced into Fixnum (TypeError)


on the following line


print d + double


Which I don't understand since none of those two variables is a string.


i = 4
d = 4.0
s = 'HackerRank'

# Declare second integer, double, and String variables.
intOne = 12
double = 4.0
string = "is the best place to learn and practice coding!, we get HackerRank is the best place to learn and practice coding!"

# Read and save an integer, double, and String to your variables.
intOne = gets.chomp
double = gets.chomp
string = gets.chomp
# Print the sum of both integer variables on a new line.
print i + intOne
# Print the sum of the double variables on a new line.
print d + double
# Concatenate and print the String variables on a new line
print s + string
# The 's' variable above should be printed first.




Answer

You must call method .to_s on your integer/ float if you want add it to something string

for example:

i = 3
b = ' bah '

c = i.to_s + b 
# => '3 bah'

or if you have string like this: '3', and you want get from this string integer you must call to_i method if you want iteger, to_f it you want float

for example:

i = '3'
g = i.to_f
# => 3