2014-01-22 23 views
0

我正在學習Ruby,並面臨一些問題。我試圖比較表達式的總和與整數,並得到這個返回:「比較字符串與2000失敗」。非常感謝!如何比較表達式的總數與Ruby中的整數?

puts "Hello! Please type here your birthday date." 

puts "Day" 
day = gets.chomp 
day.capitalize! 

puts "Month" 
month = gets.chomp 
month.capitalize! 

puts "Year" 
year = gets.chomp 
year.capitalize! 

if month + day + year > 2000 
    puts "Sum of all the numbers from your birthday date is more than 2000" 
else month + day + year < 2000 
    puts "Sum of all the numbers from your birthday date is less than 2000" 
end 
+1

大寫的整數?爲什麼? –

+0

@YevgeniyAnfilofyev:他們變大:) –

+0

當然,再投資;) –

回答

1
day = gets.chomp 

這裏day是一個字符串。而month + day + year也是一個字符串,只有更長。要獲得整數,請致電.to_i

day = gets.to_i # to_i will handle the newline, no need to chomp. 
       # repeat for month and year 

當然,一旦你轉換字符串整數,你將無法利用它們。它無論如何沒有意義。

+0

它的工作原理!謝謝!似乎我沒有讀到這一點。 –

+0

@TarasSpivak:不要忘記接受有用的答案。 :) –