i've seen both of these syntaxes before and have also used both in my own models: class Foo def get_bar @bar end end and class Foo def get_bar self.bar end end seemingly with no difference... i'm a nuby though so could anyone enlighten me to the differences if there are any? thanks, jeff
on 2007-04-06 06:30
on 2007-04-06 07:05
@bar is an instance variable... self.bar would be a method. Try doing this code in irb and you'll see that calling get_bar in the first version returns nil, while calling it on the second version throws a NoMethodError. b
on 2007-04-06 19:58
aha! i guess then the reason it has worked in RoR models is due to AR creating attr_accessors for the table columns, so calling model.some_col was returning @some_col... thanks for clearing that up
on 2007-04-06 22:00
Jeff Emminger wrote: > i've seen both of these syntaxes before and have also used both in my > own models: > > class Foo > def get_bar > @bar > end > end > > and > > class Foo > def get_bar > self.bar > end > end > > seemingly with no difference... i'm a nuby though so could anyone > enlighten me to the differences if there are any? > > thanks, > jeff This can be a real Gotcha in ActiveRecord. AR uses the *_missing methods to give the illusion that it knows what columns you have in your table. I believe that using the instance variable (@bar) now spews lots of depreciation noeses onto stdout. Good programming practice it to used the method call because you can then override that method call in your class and massage the data before it goes out (or comes in). This can eliminate the need for the get_* functions. def bar retval = self[:bar] #do interesting thing with retval here retval end John M.