Scary-rabbit_small Daniel Waite 2 posts

I wrote this in TextMate first so I’ll paste it here…

class Dave

  # If self is Dave, why must I explicitly say self?
  #
  def self.meth
  end

  # If self is Dave, why isn't this the same as saying
  # self.another_meth?
  #
  def another_meth
  end

  # Valid...
  meth

  # Invalid...
  another_meth

end

# If I'm standing in a class definition here,
# why can I call a method not prefixed with self,
# but I can't inside the Dave class definition?
# (as shown above)

def outer_meth
  puts "Hi" 
end

def self.outer_meth_2
  puts "Hi again" 
end

# And why does this work?

outer_meth
outer_meth_2

I’ll add that I’ve never had these questions before; the differences between “class-level” and instance-level methods has always made sense to me.

But after watching this I suddenly have these questions.

I guess everything I’m asking hinges on my statement about being inside a class definition outside any visible class definition (i.e. where self == main). If I’m wrong about that then I suppose the answer is, “because that’s the way it works”.

 
Dave_8_trans_small Dave Thomas Administrator 52 posts


  class Dave

    # If self is Dave, why must I explicitly say self?
    #
    def self.meth
    end

Because def meth (without the self) would declare an instance method. You want to define a method callable on the class.

As for the top-level execution environment… well, at that point you’re actually inside something that looks like this:


class Object 
   Object.new.instance_eval do 
     def self.to_s 
       "main" 
     end 

     ## 
     # Your program gets inserted here... 
     ## 

   end 
end 
 
Scary-rabbit_small Daniel Waite 2 posts

Ah, interesting. So the def keyword always wants to make instance-level methods unless told explicitly otherwise.

I dig your illustration of where programs get written. Before it was always a black box, now I feel like I’m bootstrapped into a rocket or something. Fun stuff. :)

3 posts, 2 voices