Simple Ruby Program...Help Needed

Go To StackoverFlow.com

1

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 "?"
2012-04-05 23:52
by bclayman
This was easy enough, but in the future, it'd be better to also include the error message you get - sarnold 2012-04-05 23:56


2

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 #{}.

2012-04-06 00:06
by sepp2k
Awesome, super helpful guys. Thanks a lot - bclayman 2012-04-06 00:11
Also, how do I get spaces between strings. If I define firstname and lastname, how do I get puts firstname + lastname such that it displays "firstname lastname" instead of "firstnamelastname"? Thanks again guys - bclayman 2012-04-06 00:18
@Mariogs puts "#{firstname} #{lastname}"sepp2k 2012-04-06 00:22
How do I do it without the #{} notation? Also, what does that notation do, exactly - bclayman 2012-04-06 00:32
@Mariogs By adding a space (" ") 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


1

You're missing a + after newfavnumber and a conversion to string.

puts "how about " + newfavnumber.to_s + "?"
2012-04-05 23:54
by Ry-
Am I missing something? Adding a Fixnum to a String? I think you'd have to do this: puts "How about #{newfavnumber}?"Linuxios 2012-04-06 01:18
@Linux_iOS.rb.cpp.c.lisp.m.sh: No. I don't know Ruby that well yet. I was going to put it in anyway, but... I didn't. Sigh - Ry- 2012-04-06 13:37
Ads