开发者

Ruby: Problem adding variables

I'm making a simple Ruby program to add the letters of a person's full name, but I don't know how to add the variables in the code.

puts "What's your first name?"
first = gets.chomp
puts "What's your middle name?"
middle = gets.chomp
puts "What's your last name?"
last = gets.chomp

puts "You have " + first.length.to_s + middle.length.to_s + last.length.to_s + " letters in your name."

If I put a name like "John Jacob Smith", I get "You have 455 letters in your name" instead of "You have 14 开发者_JAVA技巧letters in your name".


puts "You have " + first.length.to_s + middle.length.to_s + last.length.to_s + " letters in your name."

first.length is 4 (a number), because "john" has 4 letters.

first.length.to_s is "4" (a string) because you turned the number into as string - too early.

In the rest of your code, you 'add' two other strings to it, to get "455"

4 + 5 = 9        # what you want
"4" + "5" = "45" # what you got


puts "You have " + (first.size + middle.size + last.size).to_s + " letters in your name."
# or
puts "You have #{first.size + middle.size + last.size} letters in your name."

or little more "Rubyish"

puts "You have " + [first, middle, last].inject(0){|s,w| s+=w.size}.to_s + " letters in your name."


Try this: puts "You have " + (first.length + middle.length + last.length) + " letters in your name."


That's because you're adding actual string representations of numbers instead of numbers thembselves. Check the @fl00r's answer

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜