The problem with your code is that the variable number
, defined inside times()
, falls method_missing()
scope of method_missing()
. Thus, when this line is executed, Ruby interprets it as a method call on self
.
In normal cases, you should get a NoMethodError
exception. However, since you have exceeded the method_missing()
method for MyClass
, you will not get this exception. Instead of calling the number(
) method.
To avoid such problems, try specifying the names of the methods that are allowed. For example, let's say you only need the try, test, and my_method
that should be called on MyClass
, then point these method names to method_missing()
to avoid such problems.
As an example:
class MyClass def method_missing(name, *args) name = name.to_s super unless ['try', 'test', 'my_method'].include? name number = 0 10.times do number = rand(100) end puts "#{number} and #{name}" end end
Unless you really need method_missing()
, do not use it. There are some good alternatives here .
source share