user626912
user626912

Reputation: 2560

When does Ruby know that a method exists?

One question that ran through my mind was how does the Ruby interpreter know that a method exists on a object if the definition is yet to be interpreted? Like, wouldn't it matter whether you define the method first than use it, rather than use it then define it?

Upvotes: 1

Views: 1589

Answers (3)

OscarRyz
OscarRyz

Reputation: 199264

The problem is, the interpreter tried to find it when you use it, and since it won't be there, it may fail.

In ( some ) compiled languages, it doesn't matter, because while compiling, the compiler may say "I'll look for this on a second pass" but I don't think this is the case with Ruby.

Upvotes: 1

Amadan
Amadan

Reputation: 198418

It doesn't know, and it doesn't care - until execution. When a method call statement is executed, the interpreter looks to see if the class (object, not code!) has the named function. If it does not, it looks up the ancestor tree. If it does not find any, it calls the method_missing method. If that is not defined, you get your error.

If your function call does not get executed, you will not get any errors.

Upvotes: 5

maerics
maerics

Reputation: 156534

The interpreter doesn't know about undefined methods ahead of time, for example:

o = Object.new
o.foo # => Raises NoMethodError.
class Object
  def foo
    puts "Foo!"
  end
end
o.foo # => prints "Foo!", since the method is defined.

However, Ruby has a neat feature called method_missing which let's the receiver of a method call take the method name and arguments as separate arguments and handle accordingly as long as no defined method already handles the call.

def o.method_missing(sym, *args)
  puts "OK: #{sym}(#{args.inspect})"
  # Do something depending on the value of 'sym' and args...
end
o.bar(1, 2, 3) #=> OK: bar(1, 2, 3)

"Method missing" is used by things like active record find methods and other places where it could make sense to have "dynamically defined" functions.

Upvotes: 3

Related Questions