2012-11-23 35 views
3

我剛開始學習Ruby,不確定是什麼導致錯誤。我正在使用紅寶石1.9.3Ruby將字符串和整數放在同一行

puts 'What is your favorite number?' 
fav = gets 
puts 'interesting though what about' + (fav.to_i + 1) 

in `+': can't convert Fixnum into String (TypeError) 

在我上一個puts語句中,我認爲它是一個字符串和計算的簡單組合。我仍然這樣做,但只是不明白爲什麼這不起作用

回答

3

(fav.to_i + 1)返回一個整數,ruby不會做隱式類型轉換。您必須通過執行(fav.to_i + 1).to_s來將其轉換爲能夠將其添加到字符串中。

+0

好吧,有點像字符串有字符串嗎?整數不能與字符串混合?感謝您的解決方案! – catchmikey

+0

是的,有點:[這是一個很好的閱讀](http://www.rubyfleebie.com/ruby-is-dynamically-and-strongly-typed/)。 –

7

在Ruby通常可以使用,而在添加(「串聯」)的字符串一起

puts "interesting though what about #{fav.to_i + 1}?" 
# => interesting though what about 43? 

基本上「串內插」時,#{}內部的任何被評估,轉換爲字符串,並插入到含有串。請注意,這隻適用於雙引號字符串。在單引號的字符串中,你會得到你準確的內容:

puts 'interesting though what about #{fav.to_i + 1}?' 
# => interesting though what about #{fav.to_i + 1}? 
相關問題