Call a method before a method is called?

B

Ben Johnson

Does ruby have "hooks". Where I can define, let's say, a method called
__before that will be called before ANY method call for that class?

Thanks for your help.
 
R

Rodrigo Bermejo

You can do it easily this way (depending what you really want):


def lady
puts "ladies go first"
end

class Myclass
lady
def initialize
end
def man
puts "you look better from here"
end
end


myclass=Myclass.new
myclass.man

/--> ladies go first
/--> you look better from here


A not OO solution is to use:

(from programming ruby book)

Every Ruby source file can declare blocks of code to be run as the file
is being loaded (the BEGIN blocks) and after the program has finished
executing (the END blocks).

BEGIN {
begin code
}

END {
end code
}


A program may include multiple BEGIN and END blocks. BEGIN blocks are
executed in the order they are encountered. END blocks are executed in
reverse order.




hope it helps

-rb.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top