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

November 11, 2007

Changing self in Ruby

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?

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/t/trackback/2226312/23250364

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

Comments

require/load change scope/self.

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

Chris:

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

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

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.

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

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.

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

I see now. Makes sense.

Post a comment

If you have a TypeKey or TypePad account, please Sign In

Now in Beta

  • Programming Ruby, 3rd Edition
    Third Edition, Covering Ruby 1.9, now in beta
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