Oleg de Leon
Oleg de Leon

Reputation: 21

Ruby: no implicit conversion of fixnum into string

Trying to solve one of the problems in Chris Pine's book. Asks users to input their first and last names, then it should display the total number of characters of both.

Here's one of many solutions I've come up with:

puts "First name?"
first_name = gets.chomp

puts "Last name?"
last_name = gets.chomp

total = first_name.length.to_i + last_name.length.to_i

puts 'Did you know you have ' + total + ' characters in your name ' + first_name + last_name + '?'

Upvotes: 2

Views: 1350

Answers (2)

Gurmukh Singh
Gurmukh Singh

Reputation: 2017

Length returns an integer (no need to convert to_i) so change your code to this:

total = first_name.length + last_name.length

Upvotes: 0

tadman
tadman

Reputation: 211560

Ruby is pretty strict about the difference between a String and an Integer, it won't convert for you automatically. You have to ask, but you can ask politely:

puts "Did you know you have #{total} characters in your name #{first_name} #{last_name}?"

You can also do the math this way:

puts "Did you know you have #{first_name.length + last_name.length} characters in your name?"

The #{...} interpolation only works inside "double-quoted" strings, but it does convert to a string whatever the result of that little block is. Single quoted ones avoid interpolation, which is sometimes handy.

If you do want to concatenate strings you have to convert manually:

"this" + 2.to_s

Upvotes: 4

Related Questions