21 Jul, 2009, Runter wrote in the 1st comment:
Votes: 0
In Ruby you can dynamically call methods on objects with send.
class Someclass;  
def some_method; puts "found"; end


results in: "found"

What isn't often reported is this example.

class Someclass; end ### no defined methods

def some_function; puts "found"; end


results in: "found"

This may result in a fallacy of believing that you are accessing something from within the scope of the object created. What actually is happening is some_function is being tucked into a subclassof Someclass: Object. Which every object inherits. So effectively you are still calling a method that belongs to your object.

So since it's effectively part of our instanced object through inheritance we can access it like this: Right?

Wrong. :P It's a private method and it'll throw the NoMethodError exception.

NoMethodError: private method `roar' called for #<Meh:0x00000000f3b3f8>

Interestingly we can do the same thing as defining a function/global method like this:

### extend the Object class which everything inherits.
class Object
def some_function; puts "found"; end

This effectively will do the same thing. It will print found when we use send from any object. (Also makes it public)

But interestingly, it also still lets you have access to it as a global function/method.


Outside of your object still accesses it, with good reason, but I think the implication is pretty obvious by this point. :d
21 Jul, 2009, kiasyn wrote in the 2nd comment:
Votes: 0
Its also good to know if you override the send method with your own stuff (ie send text to a player) you can still use __send__ as a substitute, ie:

o = Object.new
o.send( "some_function" )
o.__send__( "some function" )

achieve the same thing