2011-12-13 64 views
0

我寫了一個小程序來測試出的TextMate 2(我是相當新的紅寶石)和它吐出的是4 + 9 = 49,而不是13的某些原因。爲什麼Ruby會連接而不是添加2個值?

def add(x,y) 
    c = x + y 
    return c 
end 

puts "please enter a value " 
a = gets.chomp 
puts "please enter another value " 
b = gets.chomp 

printMe = add(a,b) 

puts printMe 
+7

因爲「4」+「9」是「49」:) – pilcrow 2011-12-13 20:05:30

+0

此時要問的一個好問題是,您是否瞭解字符串和數字的區別?那「4」+「9」=「49」應該立刻引發對發生事件的理解。 – 2012-01-28 18:05:38

回答

7

這是因爲gets返回一個字符串:

def add(x,y) 
    c = x + y 
end 

puts "please enter a value " 
a = gets.to_i 
puts "please enter another value " 
b = gets.to_i 

printMe = add(a,b) 

puts printMe 
+1

`a = gets.to_i`會做(不嚼)。 – steenslag 2011-12-13 21:37:08

0

它的治療由默認的輸入作爲字符串我想,嘗試:

def add(x,y) 
    (x.to_i + y.to_i) 
end 

而且,沒有必要在紅寶石返回或發生在變量c,它會自動地返回代碼的最後一行的輸出

0

如果你沒有puts printMe.inspect,你可以看到自己,它是"49",不49,那ab都是字符串。有關更多調試提示,請參見How do I debug Ruby scripts?

相關問題