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=
[sourcecode language="ruby"]
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
[/sourcecode]

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.
[sourcecode language="ruby"]
class Foo < AR:B
def bar
self.text = ‘fake’ #assigns the field ‘text’
text.gsub!() #changes the variable ‘text’
end
end
[/sourcecode]

This entry was posted in Uncategorized. Bookmark the permalink.

One Response to The usage of self in Ruby

  1. John conrad says:

    one more nice topic in your blog and nice comments too keep it up, If you advise some more related links to topic. I’m very interested in CMS and all its related subjects.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>