0

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)
4

1 回答 1

2

您收到该错误是因为您在数组上调用 .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 上玩起来太奇怪了,我通常就是这样尝试解决这些问题的,别忘了总是参考官方文档

于 2014-03-23T14:59:29.903 回答