Reputation: 1
The code below outputs 333 instead of 9.
How can I change it to print the sum calculation instead of the character concatenation?
puts 'What is your first name?'
first = gets.chomp
puts 'What is your middle name?'
middle = gets.chomp
puts 'What is your last name?'
last = gets.chomp
var1 = first.length.to_s
var2 = middle.length.to_s
var3 = last.length.to_s
puts 'Did you know there are ' + var1 + var2 + var3 + ' characters in your name, ' + first + ' ' + middle + ' ' + last
Upvotes: 0
Views: 97
Reputation: 9497
This will work:
puts 'What is your first name?'
first = gets.chomp
puts 'What is your middle name?'
middle = gets.chomp
puts 'What is your last name?'
last = gets.chomp
var1 = first.length
var2 = middle.length
var3 = last.length
puts "Did you know there are #{var1 + var2 + var3} characters in your name"
Notes: To add together the var
s you shouldn't convert to strings. String-interpolation requires double-quotes. Good spacing helps readability big time.
Example:
$ What is your first name?
#James
$ What is your middle name?
#Tiberius
$ What is your last name?
#Kirk
#Did you know there are 17 characters in your name
Upvotes: 1
Reputation: 160551
The problem is that Ruby understands the difference between a string and an integer/number:
'c'.class # => String
1.class # => Fixnum
You have to tell Ruby to convert from the one to the other if you want to add numbers:
'1' + '2' # => "12"
1 + 2 # => 3
To convert a String value to a number we use to_i
:
'1'.to_i + '2'.to_i # => 3
You already know that chomp
is useful to remove trailing new-lines:
"a\n" # => "a\n"
"a\n".chomp # => "a"
but when converting to a number it's not necessary. to_i
will convert the leading digits into a number and stop at the first non-digit:
"1\n".chomp.to_i # => 1
"1\n".to_i # => 1
and:
"12".to_i # => 12
"1 2".to_i # => 1
so use the easier:
"1\n".to_i # => 1
Note: to_i
can do more than just convert from decimal (base 10) representation of numbers, it can do other bases:
"10000".to_i(2) # => 16
"20".to_i(8) # => 16
"10".to_i(16) # => 16
but that's something to grow into.
Upvotes: 5
Reputation: 408
You are first converting the length of names (integer) into strings and then trying to add them to another string. That's why the length shows up as 333. Instead of converting the length into strings, leave them as is (remove .to_s). And then perform an add for the numbers and finally convert to string.
var1 = first.length
var2 = middle.length
var3 = last.length
puts 'Did you know there are ' + (var1 + var2 + var3).to_s + ' characters in your name, ' + first + ' ' + middle + ' ' + last
Upvotes: 0