Ruby - overwrite def method

How can I overwrite the def method ? But this is strange, because I do not know where the def method is derived from. This is not a module, not an object, not a BasicObject (from Ruby 1.9). And def.class don't say anything;)

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."

Thanks so much for any ideas.

+3
source share
4 answers

Who told you this defis a method? Not this. This keyword, such as class, if, end, etc. Therefore, you cannot overwrite it if you do not want to write your own ruby ​​interpreter.

+6
source

You can use alias_method.

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

:

def hello
  puts "Hello"
  yield if block_given?
end

hello do
 puts "cruel world"
end
+1

As others have said, defnot a method, this is a keyword. You cannot "override" it. You can, however, define a method called "def" using Ruby metaprogramming:

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

This will not override the keyword def, but you can call the new method with method(:def).call.

So, you are there (sort of).

Note. I have no idea why you want to define a method called def. Do not do this.

0
source

Source: https://habr.com/ru/post/1758893/


All Articles