NoMethodError .to_i ruby

时间:2013-01-25 18:15:40

标签: ruby arrays ruby-on-rails-3

ruby​​中的基本代码对我不起作用....错误指定

NoMethodError(

的未定义方法`to_i'
row = row.split(",").map { |x| x.to_i }

编辑:

NoMethodError (undefined method `to_i' for [["123,123,123,"]]:Array):
  app/controllers/sessions_controller.rb:21:in `import'
  app/controllers/sessions_controller.rb:20:in `each'
  app/controllers/sessions_controller.rb:20:in `import'
  app/controllers/sessions_controller.rb:17:in `each'
  app/controllers/sessions_controller.rb:17:in `import'


  Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
  Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.7ms)
  Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (8.2ms)

1 个答案:

答案 0 :(得分:1)

您收到该错误是因为您在数组上调用方法.to_i,这是错误的,因为该方法属于String类,来源:http://www.ruby-doc.org/core-2.1.0/String.html#method-i-to_i

所以为了解决这个问题,我们需要从数组中取出那个字符串,这样我们就可以把它变成一个整数,记住你是从一个包含数组的数组开始的,这就是为什么我这样做的原因。两次调用.pop:

    row = [["123, 123, 123"]]
    string_of_numbers = row.pop.pop
    string_of_numbers.split(",").map {|x| x.to_i }

如果感觉太奇怪,试着在irb上玩它,通常我会尝试对这些事情进行排序,不要忘记总是参考官方文档