【发布时间】:2016-08-27 10:00:40
【问题描述】:
我有一些代码:
variable = ...
case variable
when ~:new
':new method!'
when ~:lenght
':size method!'
end
对于o = [],它应该转到 size 大小写并返回 ':size method!'
对于 o = String 应该返回 ':new method'
这部分我知道如何实现(我的解决方案如下)
但它应该适用于任何类型的对象。而这部分我不知道如何实现。我不知道我的代码有什么问题,它是否正确?我的代码:
module AbstractClass
def new; false end;
def size; false end;
end
class Class
include AbstractClass
end
class Array
include AbstractClass
def size; true end;
end
class String
include AbstractClass
def new; true end;
end
class Symbol
include AbstractClass
alias ~ to_proc
end
感谢您的帮助!
【问题讨论】:
-
您可以使用缩进或使用编辑器中的
{}按钮来格式化。 -
我不太明白你想要达到什么目的。这一切的目标是什么?
-
这是练习,我给你写了练习的要点。有一些自动化测试表明我的代码不够正确。据说for Array 应该返回':size method!',for String ':new method!'它应该适用于任何一种方法。我知道的就这些
-
好吧...这是一个练习,我明白了。其他对象的预期输出是什么?
-
monkey-patch 的顶级类不是
Class,而是Object。在此处包含您的模块,它将影响任何类的每个实例。 (也有BasicObject,但Object可以。)然后您不需要将它包含在Array中,只需覆盖其中一种方法即可。
标签: ruby-on-rails ruby switch-statement metaprogramming