gpt4 book ai didi

ruby - 是否可以在 Ruby 中识别别名方法?

转载 作者:数据小太阳 更新时间:2023-10-29 06:41:31 25 4
gpt4 key购买 nike

通常在控制台中,我会询问一个对象

pp obj.methods.sort #or...
pp (obj.methods - Object.methods).sort

在 Ruby 中,开发人员为方法提供别名是很常见的。我想知道是否有一种识别别名的反射方式,以便我可以显示别名方法,比如...

array.aliased_methods #=> {:collect => :map, ...}

这有助于准确识别一个对象可以做多少事情。

最佳答案

在 Ruby 1.9 中,别名实例方法将是 eql?,因此您可以定义:

class Module
def aliased_methods
instance_methods.group_by{|m| instance_method(m)}.
map(&:last).keep_if{|symbols| symbols.length > 1}
end
end

现在如果你尝试一下,你会得到:

class Foo
def bar; 42 end
alias baz bar
def hello; 42 end
end

Foo.aliased_methods # => [[:bar, :baz]]

Array.aliased_methods # => [[:inspect, :to_s], [:length, :size]]

请注意,有些对丢失了,例如[:map, :collect]。这是由于 bug that is now fixed并将在下一个版本 (2.0.0) 如果它对你很重要,你可以滚动你自己的 group_by 而不使用哈希或 eql? 并且只使用 ==.

关于ruby - 是否可以在 Ruby 中识别别名方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3676834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com