何时在 Ruby 中使用“self" [英] When to use 'self' in Ruby

查看:53
本文介绍了何时在 Ruby 中使用“self"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种方法:

  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

date 为 nil 时失败并出现此错误:

Fails with this error when date is 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,则该方法可以正常工作.

However, if I change date = date.to_date to self.date = self.date.to_date, the method works correctly.

这是怎么回事?一般来说,我什么时候必须写self?

What's going on? In general, when do I have to write self?

它与问题无关,但请注意没有titleize!"方法.

It's not related to the question, but please note that there is no "titleize!" method.

推荐答案

每当你想在 self 上调用 setter 方法时,你必须写 self.foo = bar.如果您只写 foo = bar,ruby 解析器会将其识别为变量赋值,并从现在开始将 foo 视为局部变量.为了让解析器实现,你要调用setter方法,而不是分配一个局部变量,你必须写obj.foo = bar,所以如果对象是self,self.foo = bar

Whenever you want to invoke a setter method on self, you have to write self.foo = bar. If you just write foo = bar, the ruby parser recognizes that as a variable assignment and thinks of foo as a local variable from now on. For the parser to realize, that you want to invoke a setter method, and not assign a local variable, you have to write obj.foo = bar, so if the object is self, self.foo = bar

这篇关于何时在 Ruby 中使用“self"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆