In Ruby you can dynamically call methods on objects with send.
class Someclass; def some_method; puts "found"; end end
Someclass.new.send("some_method");
results in: "found"
What isn't often reported is this example.
class Someclass; end ### no defined methods
def some_function; puts "found"; end
Someclass.new.send("some_function");
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?
any_obj.some_function
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 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.
some_function
Outside of your object still accesses it, with good reason, but I think the implication is pretty obvious by this point. :d
results in: "found"
What isn't often reported is this example.
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:
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