在Ruby中,我可以定义一个方法foo =(bar):
irb(main):001:0> def foo=(bar)
irb(main):002:1> p "foo=#{bar}"
irb(main):003:1> end
=> nil
Run Code Online (Sandbox Code Playgroud)
现在我想检查它是否已定义,
irb(main):004:0> defined?(foo=)
SyntaxError: compile error
(irb):4: syntax error, unexpected ')'
from (irb):4
from :0
Run Code Online (Sandbox Code Playgroud)
在这里使用的正确语法是什么?我假设必须有一种方法来逃避"foo =",以便它被解析并正确传递给定义的?运营商.
添加两Set[Int]件作品:
Welcome to Scala version 2.8.1.final (Java HotSpot(TM) Server VM, Java 1.6.0_23).
Type in expressions to have them evaluated.
Type :help for more information.
scala> Set(1,2,3) ++ Set(4,5,6)
res0: scala.collection.immutable.Set[Int] = Set(4, 5, 6, 1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
但添加两个Set[Any]不是:
scala> Set[Any](1,2,3) ++ Set[Any](4,5,6)
<console>:6: error: ambiguous reference to overloaded definition,
both method ++ in trait Addable of type (xs: scala.collection.TraversableOnce[Any])scala.collection.immutable.Set[Any]
and method ++ in trait TraversableLike of type [B >: Any,That](that: scala.collection.TraversableOnce[B])(implicit bf: scala.collection.generic.CanBuildFrom[scala.collection.immutable.Set[Any],B,That])That
match argument types …Run Code Online (Sandbox Code Playgroud) 在Ruby中,我如何以编程方式确定哪个类/模块定义了被调用的方法?
在我调用的给定范围内说some_method().在同一范围内,我想调用一个函数find_method(:some_method),将返回其类,单例类或模块定义some_method.
这里有一些代码来说明我的意思:
class Foo
include ...
def bar
...
some_method() # calls a method in scope, assume it exists
find_method(:some_method) # Returns where the method is defined
# e.g. => SomeClassOrModule
...
end
end
Run Code Online (Sandbox Code Playgroud)
我猜我不得不使用的反射功能,从复杂的混合物self,用self.ancestors走了继承树,使用method_defined?检查的方法在类或模块,并且可能是一些其他技巧来检查从范围界定最里面到最外层(因为代码可以在例如a内运行instance_eval).
我只是不知道正确的顺序和Ruby的元模型的所有细微之处来实现find_method,使得它在其搜索既详尽和正确的方法分派分辨率的观点.
谢谢!