加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

何时在Ruby中使用“self”

发布时间:2020-12-16 21:35:16 所属栏目:百科 来源:网络整理
导读:这种方法: def format_stations_and_date from_station.titelize! if from_station.respond_to?(:titleize!) to_station.titleize! if to_station.respond_to?(:titleize!) if date.respond_to?(:to_date) date = date.to_date end end 当日期为nil时,此错
这种方法:
def format_stations_and_date
    from_station.titelize! if from_station.respond_to?(:titleize!)
    to_station.titleize! if to_station.respond_to?(:titleize!)
    if date.respond_to?(:to_date)
      date = date.to_date
    end
  end

当日期为nil时,此错误失败:

NoMethodError (You have a nil object when you didn't expect it!
The error occurred while evaluating nil.to_date):
  app/models/schedule.rb:87:in `format_stations_and_date'
  app/controllers/schedules_controller.rb:15:in `show'

但是,如果我将date = date.to_date更改为self.date = self.date.to_date,则该方法正常工作.

这是怎么回事?一般来说,我什么时候要写自我?

编辑:这与问题无关,但请注意,没有“标题化”!方法.

解决方法

每当你想自我调用setter方法,你必须写self.foo = bar.如果你只是写foo = bar,那么ruby解析器就可以将它作为一个变量赋值,从现在开始就将foo看作一个局部变量.要解析器实现,你想要调用setter方法,而不是分配一个局部变量,你必须写obj.foo = bar,所以如果对象是self,self.foo = bar

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读