From: Adam Gardner Date: 2009-04-02T07:02:07+09:00 Subject: Re: When to use instance variables @ Steve Dogers wrote: > Thank you to everyone who answered - yes it makes a lot more sense now! > > It made me think though - when should you use self? I know you can use > self to declare class methods but why do I see some people prefix just > about anything with self. ? Isn't 'self' implied? > > Cheers! I for one sometimes prefix methods with self to help visually distinguish them from local variables. I did this a lot when I was less experienced in ruby, and I still do it occasionally. You must specify the self receiver if you're calling an assignment method, or the interpreter will think you are trying to assign to a local variable. It's also mandatory if you have a method with the same name as a local variable, or whose name begins with a capital letter (although frankly, you probably should just change the method name or the variable name in these cases): hello = 1 def hello 2 end hello # => 1 self.hello # => 2 def Hello 3 end Hello # => NameError: uninitialized constant Hello self.Hello # => 3 I've often thought that the ruby would be just a tad bit cleaner if local variables and implicit self method calls were distinguishable from each other syntactically. Something like giving implicit self method calls a bare dot prefix. I'm sure there are a lot of people who would disagree, though, and it's unlikely to happen at this point regardless. Ah, well. -- Posted via http://www.ruby-forum.com/.