ruby-on-rails – 在Ruby on Rails中获取私有方法错误

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在Ruby on Rails中获取私有方法错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个控制器:
class StatsController < ApplicationController

  require 'time'

  def index
      @started = "Thu Feb 04 16:12:09 UTC 2010"
      @finished = "Thu Feb 04 16:13:44 UTC 2010"
      @duration_time = stats_duration(@started,@finished)
  end

  private
  def stats_duration(started,finished)
    time_taken = distance_of_time_in_words(Time.parse(started),Time.parse(finished))
    time_taken
  end

end

它接收开始和结束时间并计算时间之间的持续时间.

当我运行这个时,我收到以下错误

private method `gsub!’ called for Thu
Feb 04 16:12:09 UTC 2010:Time

为什么会这样?

解决方法

私有方法gsub!在使用Time.parse时调用通常意味着您使用Time对象而不是String调用了parse,因此听起来您的代码实际上是在尝试将时间解析两次.

例如

>> t = Time.now
=> Fri Feb 05 13:12:17 +0000 2010
>> Time.parse(t)
NoMethodError: private method `gsub!' called for Fri Feb 05 13:12:17 +0000 2010:Time
        from c:/ruby/lib/ruby/1.8/date/format.rb:965:in `_parse'
        from c:/ruby/lib/ruby/1.8/time.rb:240:in `parse'
        from (irb):6
原文链接:https://www.f2er.com/ruby/264896.html

猜你在找的Ruby相关文章