ruby - 何时在 Ruby 中使用 'self'

标签 ruby

这个方法:

  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 时出现此错误:

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,该方法将正常工作。

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

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

最佳答案

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

关于ruby - 何时在 Ruby 中使用 'self',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1252031/

相关文章:

css - Ruby on Rails 根据数据库更改 CSS 中的背景颜色

ruby - 如何为名称以问号结尾的属性定义 setter?

ruby-on-rails - 使用模块定义元类方法

ruby - 导轨 : Advantages of storing session in database?

ruby - 匹配大写字母并用后续字母填充,直到一定的字符串长度

ruby-on-rails - Ruby SSL 握手未收到服务器 Hello 返回 - 使用代理 Net::HTTP

Ruby:从二维数组中的每个子数组中获取第 n 个元素

ruby-on-rails - 如何运行两个 Zeus 服务器

Ruby,从 Date.day_fraction_to_time 获取小时、秒和时间

ruby - 升级ruby后无法连接到redis