Ui-Gyun Jeong
Ui-Gyun Jeong

Reputation: 153

How do I add these two variables?

puts "first number please"
first = gets.chomp

puts "Second number please"
second = gets.chomp

answer = first + second
puts "The calculation is #{first} + #{second} = " + answer.to_s

I summed two variables first and second

If first == 1 and second == 2 then answer should be 3, but ruby shows 12 What is the problem?

What I tried is

answer = first.+(second)

Upvotes: 0

Views: 4013

Answers (4)

White Tiger
White Tiger

Reputation: 31

So your problem here is that you are trying to get sum of 2 strings which is not going to work, you need to first turn it into a integer by replacing .chomp with .to_i and then you can use it like you were using it, but remember that if you want decimal number for example if you are doing division you need to use .to_f to make it float to get the more accurate answer in decimals

puts("Give first number")
number_one = gets.to_i
puts("Give second number")
number_two = gets.to_i
sum = number_one + number_two
puts("Answer is: #{sum}")

Upvotes: 1

SG 86
SG 86

Reputation: 7078

puts "first number please"
first = gets.chomp
puts "Second number please"
second = gets.chomp
answer = first.to_i + second.to_i
puts "The calculation is #{first} + #{second} = #{answer}" 

Console:

[3] a = gets.chomp
2
=> "2"
[4] a.class
=> String
[5] a = a.to_i
=> 2
[6] a.class
=> Fixnum

Upvotes: -1

Yu Hao
Yu Hao

Reputation: 122383

Thant's because gets returns a string. So the + operator in answer = first + second applies to string concatenation. Change it to:

puts "first number please"
first = gets.to_i
puts "Second number please"
second = gets.to_i

Upvotes: 3

Darvex
Darvex

Reputation: 3644

The numbers you got were actually strings, so when you used "+" ruby concatenated them. You should try

gets.to_i

Upvotes: 0

Related Questions