Reputation: 320
say I have this:
class Post
def initialize()
vote_total = 0
end
end
Obviously, this won't set an instance variable, and to do so, inside initialize this needs to be written
self.vote_total = 0
My question is...what is self inside the initialize method?
irb(main):022:0> class Post
irb(main):023:1> puts self
irb(main):024:1> def initialize()
irb(main):025:2> puts self
irb(main):026:2> vote_total = 0
irb(main):027:2> puts self
irb(main):028:2> end
irb(main):029:1> end
Post
=> nil
irb(main):030:0> post = Post.new
#<Post:0x007f9448d76f98>
#<Post:0x007f9448d76f98>
=> #<Post:0x007f9448d76f98>
I understand the difference but functional similarity between
@instance_variables
obj.method_instance_variables
but I don't understand whats going on in that vote_total line. what is self there, and what is getting vote_total defined?
Upvotes: 1
Views: 3649
Reputation: 44725
initialize
is an instance method so self
refers to new instance of the class. When you execute self
outside of any method (in class body), self refers to the class itself).
OTHER NOTES:
Neither of:
vote_total = 0
self.vote_total = 0
set an instance variable 'per se'. First call creates local variable vote_total
, second call executes method vote_total=
. If your class has attr_accessor
or attr_reader
on top, then this method is defined as
def vote_total=(value)
@vote_total = value
end
which is setting the variable. If you have none of those and you don't define it any other way (number of ways is extremely huge), then self.vote_total = :foo
will raise undefined method 'vote_total='
exception.
Upvotes: 3