The usage of self in Ruby

This confused me for some time and I figured I write it down for others to enjoy. When should one use the keyword self in AR:B? For this it is important to realise that Ruby is an interpreted language. Whenever Ruby sees an assignment like bla = 'boe' it first looks for a local varialbe by that name(bla in this case) and if that does not exists it then looks for a method bla=


class Foo
  def bar
    text = 'fake' #assigns a variable 'text'
    text.gsub!() #changes the variable 'text'
  end

  def bla
    text.gsub!() #does not find a variable 'text', then searches for a method 'text'(and fails in this case)
  end
end

So if you want to change a field in an ActiveRecord model you need to tell Ruby not to create a local variable but to use the generated setter method.


class Foo < AR:B
  def bar
    self.text = 'fake' #assigns the field 'text'
    text.gsub!() #changes the variable 'text'
  end
end

Leave a Reply