How many ways are there to change self in Ruby? I count (excluding thread switching):
- method invocation
- class and module definition
- instance_ and class/module_eval
- invocation of a proc
What am I missing?
« Michael Swaine on Computer Book Publishing | Main | Looking for a wiki »
TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00d83451c41c69e200e54f8056e68833
Listed below are links to weblogs that reference Changing self in Ruby:
This is only a preview. Your comment has not yet been posted.
As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.
Having trouble reading this image? View an alternate.
require/load change scope/self.
Posted by: ko1 | November 11, 2007 at 07:13 PM
The value of self does change in a method definition, in which it's nil. This scenario could be considered distinct from "class and module definition".
Posted by: Chris Bernard | November 11, 2007 at 11:44 PM
Chris:
I'm intrigued: how is it possible to tell from the Ruby level what the value of self is during a method definition?
Posted by: Dave Thomas | November 12, 2007 at 08:58 AM
ko1:
I believe self is unchanged by require, but the scoping is changed so that local variables aren't accessible. If you set an instance variable in a required file, though, it is accessible after the require.
Dave
Posted by: Dave Thomas | November 12, 2007 at 08:59 AM
I'm not getting how self changes with the invocation of a Proc. Scope definitely changes, but self? It seems like the same kind of change as require/load.
Posted by: JEG2 | November 12, 2007 at 07:45 PM
I meant that:
----------------------------
# a.rb
class C
p self #=> C
require 'b'
end
----------------------------
# b.rb
p self #=> main
----------------------------
The reason why I posted this comment is I implemented it on YARV :)
Posted by: ko1 | November 12, 2007 at 07:53 PM
Dave:
Well, I was wrong. While playing around I had written this:
$cself; $mself
class C
$cself = self
def meth; $mself = self; end
end
p $cself # => C
p $mself # => nil
... so I mistakenly thought that self was nil while in a method definition.
But it turns out of course that the assignment to the global $mself within the method definition does not happen at all. The value of $mself is only nil because that's its initial value.
Posted by: Chris Bernard | November 13, 2007 at 12:39 AM
JEG2: What he means is this:
class B
def foo
p self
yield
end
def inspect
"a B object"
end
end
B.new.foo { p self }
When run, this gives:
a B object
main
Posted by: Ken Bloom | November 15, 2007 at 03:29 PM
I see now. Makes sense.
Posted by: JEG2 | November 16, 2007 at 08:06 AM