我有这段代码:
inventory_amount = columns[17] # returns a string "0000221"
puts "inventory_amount = #{inventory_amount}"
hello = inventory_amount.to_i
puts "hello = #{hello}"
但这是吐出来的:
inventory_amount = "0000221"
hello = 0
发生了什么事?在我的控制台中它可以工作:
1.9.3p362 :033 > w = "0000019"
=> "0000019"
1.9.3p362 :034 > w.to_i
=> 19
我正在使用Rails 3和Ruby 1.9.3
===更新===
可能是因为它来自文件??
File.open(file).each_line do |line|
columns = line.split(",")
isbn = columns[0]
inventory_amount = columns[17].to_i
puts "inventory_amount = #{inventory_amount}" #this still doesn't work
是的我确定列[17]是一个字符串:
inventory_amount = columns[17]
puts "inventory_amount = #{inventory_amount.class}"
打印出来:
inventory_amount = String
答案 0 :(得分:0)
尝试:
inventory_amount = columns[17].to_i
这样,首先不会发生任何其他转换。