Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialStrahinja Rodic
1,212 Pointsusing variables + gets
hello i wrote this: def add(a,b) c=a+b puts c end puts "Enter a and b\n" a=gets b=gets add(a,b)
and as output i get to enter a and b which is regular and then it retypes a and b check out the ss: http://prntscr.com/98am33
and what i want is to get a+b for instance: a=gets #I input 3 b=gets #Here I input 5 c=a+b #c suppose to be 8 why I get this output in console?
Regards! :)
1 Answer
Abigail Glunn
10,068 PointsJust by adding .chomp.to_i to a and b the code works (by default the gets user entry is a string):
def add(a, b)
c = a + b
puts c
end
puts "Enter a and b"
a = gets.chomp.to_i
b = gets.chomp.to_i
add(a, b)
But I'd probably skip "c" altogether and write "puts add(a, b)" like in the below:
def add(a, b)
a + b
end
print "Enter a: "
a = gets.chomp.to_i
print "Enter b: "
b = gets.chomp.to_i
puts add(a, b)
Edit - Haha of course for something more complicated might be useful to have c as part of the method, just figured I'd show it's not necessary ; )
Tim Knight
28,888 PointsTim Knight
28,888 PointsI definitely agree. I try to keep
puts
out of my methods altogether.