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 "?"
1
  • 3
    This was easy enough, but in the future, it'd be better to also include the error message you get. Commented Apr 5, 2012 at 23:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@Mariogs puts "#{firstname} #{lastname}"
How do I do it without the #{} notation? Also, what does that notation do, exactly?
@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.
1

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

puts "how about " + newfavnumber.to_s + "?"

2 Comments

Am I missing something? Adding a Fixnum to a String? I think you'd have to do this: puts "How about #{newfavnumber}?"
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.