简体   繁体   English

Ruby - 覆盖def方法

[英]Ruby - overwrite def method

How can I overwrite the def method? 如何覆盖def方法? But it's strange, cause I don't know from where the def method is defined. 但这很奇怪,因为我不知道def方法的定义。 It's not Module, not Object, not BasicObject (of Ruby 1.9). 它不是Module,不是Object,不是BasicObject(Ruby 1.9)。 And def.class don't say nothing ;) 并且def.class什么都不说;)

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. 非常感谢,任何想法。

Who told you def is a method? 谁告诉你def是一种方法? 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. 它是一个关键字,如classifend等。所以你不能覆盖它,除非你想编写自己的ruby解释器。

You could use alias_method. 你可以使用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. 正如其他人所说, def不是一种方法,它是一个关键词。 You can't "override" it. 你无法“覆盖”它。 You can, however, define a method called "def" via Ruby metaprogramming magic: 但是,您可以通过Ruby元编程魔术定义一个名为“def”的方法:

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 . 这仍然不会覆盖def关键字,但您可以使用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 . 注意:我不知道你为什么要定义一个名为def的方法。 Don't do it. 不要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM