3

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.

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I think it's better for me to just use some DSL blocks ;)
1

You could use alias_method.

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

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.