Puru puru rin..
Puru puru rin..

Reputation: 511

Ruby - overwrite def method

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.

Upvotes: 3

Views: 1820

Answers (4)

GMA
GMA

Reputation: 6096

As others have said, def isn't a method, it's a keyword. You can't "override" it. You can, however, define a method called "def" via Ruby metaprogramming magic:

define_method :def do
  puts "this is a bad idea"
end

This still won't override the def keyword, but you can call your new method with method(:def).call.

So, there you (sort of) have it.

Note: I have no idea why you'd ever want to define a method called def. Don't do it.

Upvotes: 0

timurb
timurb

Reputation: 5554

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

Upvotes: 1

Jason Noble
Jason Noble

Reputation: 3766

You could use alias_method.

alias_method :orig_hello, :hello
def hello
  puts "Hello!"
  orig_hello
end

Upvotes: 1

alex.zherdev
alex.zherdev

Reputation: 24174

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.

Upvotes: 6

Related Questions