Rails:将“0000221”(字符串)变为221(整数)的问题?

时间:2013-12-06 22:42:45

标签: ruby-on-rails

我有这段代码:

  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

1 个答案:

答案 0 :(得分:0)

尝试:

inventory_amount = columns[17].to_i

这样,首先不会发生任何其他转换。