Brad Hodges Brad Hodges - 11 days ago 5
Ruby Question

Most efficient way to add a method in ruby?

What is the most CPU efficient way to add a method to an object?

This is what I have now,

@pmacio.define_method(:waitfor) do |*args|
c = @pmacio.read(1)
until args[0] =~ c do
c = @pmacio.read(1)
end
end


called like:

@pmacio.waitfor(/\cF|\cG/)


But there are other ways:
define_singleton_method
etc. This method is called in the idle loop of a GNOME 2.0 based app and it needs to be as CPU efficient as possible.

EDIT: the accepted answer would look like:

def @pmacio.waitfor(c)
....
end

Answer

Your code defines a method on the value of the instance variable @pmacio, not on the instance variable itself, which is not an object.

Suppose

h = { :a => 1 }
@pmacio = h

Then

def @pmacio.my_method
  "meow"
end
  #=> :my_method

so now

@pmacio.my_method
  #=> "meow"

but if we change the value of @pmacio:

@pmacio = "cat"

we find

@pmacio.my_method
  #=> NoMethodError: undefined method `my_method' for "cat":String

That is because you have defined a method on h:

h.my_method
  #=> "meow"

You might as well write

def h.my_method
  "meow"
end

in the first place, and then execute

@pmacio = h

The upshot is that this question has nothing to do with instance variables.

Note you cannot define methods on certain objects:

def 1.my_method
end
  #=> #SyntaxError: (irb):861: syntax error, unexpected tINTEGER
Comments