« Michael Swaine on Computer Book Publishing | Main | Looking for a wiki »

November 11, 2007

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00d83451c41c69e200e54f8056e68833

Listed below are links to weblogs that reference Changing self in Ruby:

Comments

ko1

require/load change scope/self.

Chris Bernard

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".

Dave Thomas

Chris:

I'm intrigued: how is it possible to tell from the Ruby level what the value of self is during a method definition?

Dave Thomas

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

JEG2

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.

ko1

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 :)

Chris Bernard

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.

Ken Bloom

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

JEG2

I see now. Makes sense.

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

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.

Working...

Post a comment

Now in Beta

  • Programming Ruby, 3rd Edition
    Third Edition, Covering Ruby 1.9, now available
My Photo

Pragmatic Stuff

Photos

  • www.flickr.com
    This is a Flickr badge showing public photos from pragdave tagged with pragdave_badge. Make your own badge here.

Site Search

  • Google Search

    The web
    PragDave