尽管使用了 "to_i",但没有将 Fixnum 隐式转换为 String
No implicit conversion of Fixnum into String, though "to_i" is used
我正在执行 "Learn to Program" 中 Chris Pine 的任务。该程序询问一个人最喜欢的号码,加上 +1,然后显示结果。我写了这个:
puts 'Hello, what\' your favorite number?'
number = gets.to_i
puts 'Here\' a better bigger favorite number - ' + number + 1
它返回了这个:
Better_number.rb:3:in \'+\': no implicit conversion of Fixnum into String (TypeError)
我也试过了
number = gets.chomp.to_i
但这似乎不起作用。
尝试:
puts "Here\' a better bigger favorite number - #{number + 1}"
您不能将字符串与数字相加。
您不能将数字添加到 ruby 中的字符串。你必须把它变成一个字符串。
puts 'Hello, what\' your favorite number?'
number = gets.to_i
puts 'Here\' a better bigger favorite number - ' + (number + 1).to_s
# or
bigger_number = number + 1
puts 'Here\' a better bigger favorite number - ' + bigger_number.to_s
# or
puts "Here's a better bigger favorite number - #{bigger_number}"
您可以使用 #{"interpolation"}
来解决您的问题。
puts 'Hello, what\' your favorite number?'
number = gets.to_i
puts 'Here\' a better bigger favorite number - #{number + 1}'
我正在执行 "Learn to Program" 中 Chris Pine 的任务。该程序询问一个人最喜欢的号码,加上 +1,然后显示结果。我写了这个:
puts 'Hello, what\' your favorite number?'
number = gets.to_i
puts 'Here\' a better bigger favorite number - ' + number + 1
它返回了这个:
Better_number.rb:3:in \'+\': no implicit conversion of Fixnum into String (TypeError)
我也试过了
number = gets.chomp.to_i
但这似乎不起作用。
尝试:
puts "Here\' a better bigger favorite number - #{number + 1}"
您不能将字符串与数字相加。
您不能将数字添加到 ruby 中的字符串。你必须把它变成一个字符串。
puts 'Hello, what\' your favorite number?'
number = gets.to_i
puts 'Here\' a better bigger favorite number - ' + (number + 1).to_s
# or
bigger_number = number + 1
puts 'Here\' a better bigger favorite number - ' + bigger_number.to_s
# or
puts "Here's a better bigger favorite number - #{bigger_number}"
您可以使用 #{"interpolation"}
来解决您的问题。
puts 'Hello, what\' your favorite number?'
number = gets.to_i
puts 'Here\' a better bigger favorite number - #{number + 1}'