[#3986] Re: Principle of least effort -- another Ruby virtue. — Andrew Hunt <andy@...>

> Principle of Least Effort.

14 messages 2000/07/14

[#4043] What are you using Ruby for? — Dave Thomas <Dave@...>

16 messages 2000/07/16

[#4139] Facilitating Ruby self-propagation with the rig-it autopolymorph application. — Conrad Schneiker <schneik@...>

Hi,

11 messages 2000/07/20

[ruby-talk:03867] Re: main.method

From: Dave Thomas <Dave@...>
Date: 2000-07-06 11:53:50 UTC
List: ruby-talk #3867
Aleksi Niemel<aleksi.niemela@cinnober.com> writes:

> How I can make this work, that is to print blop and blop instead of blop and
> burp? How to call methods defined in Object just like methods in any other
> class? That means the method don't get wrong self?
> 
> I thought main.burp would deal with the problem, but it seems that I can't
> access main.

'main' is just the global object's representation under to_s. It isn't 
a variable or reserved word.

A second problem is that methods defined at the top-level are private, 
so they cannot be called with a receiver, so you can't go messing with 
their owning object without doing some messing, such as:

     class Fish
       def initialize
         @burp = "burp"
       end
       def burp(global)
         puts global.globalBurp
       end
     end

     @burp = "blop"

     def globalBurp
       p self
       @burp
     end

     public :globalBurp
     puts globalBurp, "\n"

     puts "now I expect fish to (blobal) burp, which means 'blop'"
     Fish.new.burp(self)

     ######################
     Outputs:

     #<Object:0x40197d30 @burp="blop">
     blop 

     now I expect fish to (blobal) burp, which means 'blop'
     #<Object:0x40197d30 @burp="blop">
     blop


Another way would be to use the special TOPLEVEL_BINDING to get to
those instance variables:

     class Test
       def printTop
         puts eval("@top", TOPLEVEL_BINDING)
       end
     end

     @top = "this is top"
     Test.new.printTop


However, I'm forced to ask -- why would you ever want to do this?


Regards


Dave

In This Thread