ruby - Does self ALWAYS refer to the current instance in an instance method definition? -
i understand question in instance method, self
refers current instance of class. true no matter how many layers of methods or loops deep in within instance method definition?
generally, yes, though there metaprogramming methods can strange things self - instance, object#instance_eval allows pass block evaluated in context of instance. in case, self within block of other instance, so:
class foo end class bar def wacky puts self.class #"bar" foo.new.instance_eval puts self.class #"foo" end end end
without careful reading, might tempted think self
within block refers bar instance, not so.
so see, purposes, can assume self self bound when entering method. although have ability pass blocks around different binding, self
doesn't re-bound "by accident" in ruby. more interesting reading, might @ ruby binding class' documentation.
Comments
Post a Comment