从 Ruby 中的方法中检索 Method 实例 [英] Retrieving the Method instance from within a method in Ruby

查看:42
本文介绍了从 Ruby 中的方法中检索 Method 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是如何确定定义方法的类的后续问题?(希望你不介意相似)

This is a follow-up question to How to determine the class a method was defined in? (hope you don't mind the similarity)

给定一个类层次结构,一个方法可以检索它自己的Method实例吗?

Given a class hierarchy, can a method retrieve its own Method instance?

class A
  def foo
    puts "A#foo: `I am #{method(__method__)}'"
  end
end

class B < A
  def foo
    puts "B#foo: `I am #{method(__method__)}'"
    super
  end
end

A.new.foo
# A#foo: `I am #<Method: A#foo>'

B.new.foo
# B#foo: `I am #<Method: B#foo>'
# A#foo: `I am #<Method: B#foo>' # <- A#foo retrieves B#foo

这样 B.new.foo 代替打印

# B#foo: `I am #<Method: B#foo>'
# A#foo: `I am #<Method: A#foo>' # <- this is what I want

在上一个问题中,Jörg W Mittag 怀疑检索方法在其中定义的类可能会违反面向对象范式.这也适用于这里吗?

In the previous question, Jörg W Mittag suspected that retrieving the class a method was defined in might violate object-oriented paradigms. Does this apply here, too?

方法不应该知道自己"吗?

Shouldn't a method "know itself"?

推荐答案

我发现了一个 方法正是这样做的.

I found a method that exactly does that.

class A
  def foo
    puts "A#foo: `I am #{method(__method__).super_method || method(__method__)}'"
  end
end

我真的很佩服 Matz 和 Ruby 核心开发人员.这种方法的存在,意味着他们心里已经有了这样的情况,并且已经想好要怎么办了.

I really admire Matz and the Ruby core developers. The existence of such method means that they had in mind such situation, and had thought about what to do with it.

这篇关于从 Ruby 中的方法中检索 Method 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆