Just trying to write a simple Ruby program here. I'm trying to get the program to ask for the user's favorite number and then suggest a new favorite number that's one greater. What's wrong with the code below?
puts "hey, whats your favorite number?"
favnumber = gets.chomp
newfavnumber = favnumber.to_i + 1
puts "how about " + newfavnumber "?"
puts "how about " + newfavnumber "?"
First of all, you probably wanted a +
before the "?"
there. The way this is written now, it parses as puts("how about " + newfavnumber("?"))
, i.e. you're calling a function called newfavnumber
, which is obviously not what you want.
However if you change it to puts "how about " + newfavnumber + "?"
, which you presumably intended, it still won't work: newfavnumber
is a number and "how about "
is a string. In ruby you can't add numbers to strings. To fix this you can call to_s
on newfavnumber
to convert it to a string.
A better way to write this would be using string interpolation: puts "how about #{newfavnumber}?"
. This way you don't need to call to_s
because you can use any type inside #{}
.
puts "#{firstname} #{lastname}"
sepp2k 2012-04-06 00:22
" "
) between the two strings. What #{}
does is it evaluates the expression inside the braces and inserts the result in the string - sepp2k 2012-04-06 00:34
You're missing a +
after newfavnumber
and a conversion to string.
puts "how about " + newfavnumber.to_s + "?"
Fixnum
to a String
? I think you'd have to do this: puts "How about #{newfavnumber}?"
Linuxios 2012-04-06 01:18