开发者

Ruby - overwrite def method

开发者 https://www.devze.com 2023-01-11 10:32 出处:网络
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 noth

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!"
# =>开发者_如何学Python "cruel world."

Many thanks, for any ideas.


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.


You could use alias_method.

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号