Mixing define_function and class methods

Hi,
I’m sure if I’m missing something fundamental, but when you run the
code below with comments intact it won’t execute, claiming that:

…/test.rb:13:in something': undefined methodsome_function’ for
#<B:0x2b9c102564a8> (NoMethodError)
from …/test.rb:30

When the comments are removed, the code will run. The thing I can’t
understand is why, when the comments are in-place, the call to
some_function from within an instance of B doesn’t work. Can anyone
point me in the right direction?

Thanks,
Garret

class A
def self.some_function(param)
puts “param: #{param}”
end

def some_function(*args)

puts self

B.some_function(*args)

end

def self.register(name, &block)
    define_method(name) do |*args|
        some_function("thing")
        block.call(args)
    end
end

def initialize
    puts "I'm a #{self.class}"
end

end

class B < A
register :something do |*args|
some_function(“something”)
end
end

b = B.new
b.something

On 10/22/07, Garret K. [email protected] wrote:

some_function from within an instance of B doesn’t work. Can anyone
point me in the right direction?

I’m not sure what you’re actually trying to accomplish, so I can’t
really fix it but.

class A
def self.some_function(param)
puts “param: #{param}”
end

Okay, now you’ve got a class method named some_function defined in A.

def some_function(*args)

puts self

B.some_function(*args)

end

If you uncomment this it defines an instance method in A also called
some_function.

def self.register(name, &block)
    define_method(name) do |*args|
        some_function("thing")
        block.call(args)
    end
end

This will define an instance method in A or a subclass, which is named
whatever is passed in the name argument.

The body of this method will call the instance method some_function on
the receiver and then evaluate the block passed into register.

def initialize
    puts "I'm a #{self.class}"
end

end

class B < A
register :something do |*args|
some_function(“something”)
end
end

Now you call the register method you defined passing :something to be
used as the name, this effectively is as if you’d coded:

class B
def something(*args)
some_function(“thing”)
some_function(“something”)} # although this would really
evaluate the block if you ever got here
end

b = B.new
b.something

WIth the code commented out, you never defined an instance method
some_function.


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/