tags:

views:

43

answers:

3

Hi,

How can I overwrite the def method? But it's strange, cause I don't know from where the def method is defined. It's not Module, not Object, not BasicObject (of Ruby 1.9). And def.class don't say nothing ;)

I would like to use something like:

sub_def hello
  puts "Hello!"
  super
end

def hello
  puts "cruel world."
end

# ...and maybe it could print:
# => "Hello!"
# => "cruel world."

Many thanks, for any ideas.

+2  A: 

Who told you def is a method? It's not. It's a keyword, like class, if, end, etc. So you cannot overwrite it, unless you want to write your own ruby interpreter.

neutrino
Thanks. I think it's better for me to just use some DSL blocks ;)
Puru puru rin..
A: 

You could use alias_method.

alias_method :orig_hello, :hello
def hello
  puts "Hello!"
  orig_hello
end
Jason Noble
A: 

You can use blocks to do some similar things like this:

def hello
  puts "Hello"
  yield if block_given?
end

hello do
 puts "cruel world"
end
erthad