1

Basic Ruby gets.chomp

 2 years ago
source link: https://www.codesd.com/item/basic-ruby-gets-chomp.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Basic Ruby gets.chomp

advertisements

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"


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.

Tags ruby

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK