这个方法:
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/