When to use 'self' in Ruby

后端 未结 2 897
春和景丽
春和景丽 2020-11-30 10:28

This method:

  def format_stations_and_date
    from_station.titelize! if from_station.respond_to?(:titleize!)
    to_station.titleize! if to_station.respond         


        
2条回答
  •  -上瘾入骨i
    2020-11-30 11:13

    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

提交回复
热议问题