Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
devon offutt
1,744 PointsObjects, Classes, and Variables extra credit
Ok so i am attempting to count the number of letters that are in the name, but im getting a
name.rb:7:in `+': can't convert Fixnum into String (TypeError)
from name.rb:7:in `<main>'
error when it is ran. here is the code. Any help would be nice :)
puts "Enter your name"
name = gets.chomp
a = 0
while a < name.length do
a = a + 1
end
if a > 25
puts "Name to long!"
else
puts name + " " + a
end
1 Answer
Chris Shaw
26,676 PointsHi Devin,
Looking at your code you're taking a very long approach to something that doesn't need to be, the biggest hurdle you've given yourself is adding a while loop where no loop needs to occur, because you're getting the user input all you need to do is check the length of the name variable in your if statement and from there output the correct string.
puts "Enter your name"
name = gets.chomp
if name.length > 25
puts "Name to long!"
else
puts "#{name} #{name.length}"
end
The original problem you were having was been caused by the below line.
puts name + " " + a
Why? In Ruby you can't convert integers to strings on the fly, you either need to use interpolation like I have above or the to_s method which means to string.
devon offutt
1,744 Pointsdevon offutt
1,744 PointsThanks! This worked and I understand everything but the #{name} and #{name.length}. I get that the first one just prints the name but why do you need the #?
Chris Shaw
26,676 PointsChris Shaw
26,676 PointsIn Ruby the pound or hash as it's known tells the compiler that interpolation it about to occur so it needs to parse whatever is inside of the curly braces as executable code, without this the compiler would breeze right past it and parse as it a normal string.
devon offutt
1,744 Pointsdevon offutt
1,744 PointsThanks!
Chris Shaw
26,676 PointsChris Shaw
26,676 PointsNo worries, happy coding =)