From: Robert Klemme Date: 2009-05-03T00:35:02+09:00 Subject: Re: Help me understand 'self' vs current object On 02.05.2009 17:24, C. Dagnon wrote: > I'm pretty mystified by this, so I would appreciate any insights... > This does involve a Rails/ActiveRecord object, but that shouldn't matter > here, right? > > I'm archiving an object when it gets deleted, so I'm chaining methods in > a Rails controller: > triplet.archive(@user.id).as_delete.save > > But I checked the database and the flag never got reset from false. I > added some print statements to as_delete() to get this: > > class ArchiveTriplet < ActiveRecord::Base > def as_delete > puts "MARKING: #{is_deleted}" > is_deleted = true > puts "MARKED: #{is_deleted}/#{self.is_deleted}" > return self > end > end > > With an additional debug after as_delete() the log shows: > MARKING: false > MARKED: true/false > ARCHIVING: #[ArchiveTriplet..., is_deleted: false, ...] > > What?! > > The easy solution is to change is_deleted everywhere to self.is_deleted, > but am I misunderstanding what 'self' is supposed to be? Is there > another keyword which means what I've been lead to believe 'self' should > mean? (ie. 'this' in Java) You just tripped into the local variable trap. The very moment you placed "is_deleted = true" in that code you told Ruby to allocate a local variable which is called "is_deleted" and whose value is "true". When you place the explicit receiver "self." before "is_deleted" Ruby chooses the method which accesses object state and not the local variable. http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#S3 Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/