Evan
Evan

Reputation: 51

Basic Ruby gets.chomp

I'm new to programming and I'm trying to answer this basic question.

Write a program which asks for a person's favorite number. Have your program add one to the number, then suggest the result as a bigger and better favorite number.

This is what I have to far, but it won't convert to a number.

    puts "What is your favorite number?"
    number = gets.chomp
    number = number.to_i + 1
    puts "I suggest " + number + " as a bigger and better number"

Upvotes: 1

Views: 11191

Answers (3)

Bogdan David
Bogdan David

Reputation: 51

As in many other problems in ruby there are a lot of ways to do it....without the three solutions writed above there is two more:

puts "What is your favorite number?"
number = gets.chomp.to_i
puts "I suggest %d as a bigger and better number" % [number + 1]

and one wich is almost the same:

puts "What is your favorite number?"
number = gets.chomp.to_i
num = number + 1
puts "I suggest %d as a bigger and better number" % [num]

Upvotes: 5

Alfonso
Alfonso

Reputation: 759

You can do it this way:

print 'What is your favorite number? '
number = gets.chomp
puts "I suggest #{number.to_i + 1} as a bigger and better number"

There is not to much to explain about the code, but there are few things to take into account:

  1. If you are rendering plain text use 'text' instead of "text". "In the double-quoted case, Ruby does more work. First, it looks for substitutions (sequences that start with a backslash character) and replaces them with some binary value" - Programming ruby 1.9.3
  2. Always try to reduce the number of lines of code.

This things are really insignificant here, but when you are coding a big program, web page etc., it really makes a difference.

Upvotes: 2

Chris Schmich
Chris Schmich

Reputation: 29466

Look more closely at the error you get:

What is your favorite number?
42
number.rb:4:in `+': can't convert Fixnum into String (TypeError)
    from number.rb:4:in `<main>'

Line 4 is:

puts "I suggest " + number + " as a bigger and better number"

The problem is that Ruby won't implicitly convert number into a string (e.g. "foo" + 42 is not valid in Ruby). There are a couple of solutions:

  1. Call to_s on number to convert it to a string before concatenating:

    puts "I suggest " + number.to_s + " as a bigger and better number"
    
  2. Use Ruby string interpolation:

    puts "I suggest #{number} as a bigger and better number"
    

Option 2 is more idiomatic, I suggest using that.

Upvotes: 11

Related Questions