简体   繁体   English

传递的方法名称与类的instance_methods之间没有匹配项

[英]There is no match between the passed method name and the instance_methods of class

I am getting the name of a method dynamically and I am passing it for a check like this: 我正在动态获取方法的名称,并通过它进行如下检查:

if @myObject.class.instance_methods.include?(the_passed_method_name.to_sym) then
 # Something
else
 # Some other thing
end

lets say that I have passed "length" or "reverse" and I make the check for the class "String" and they work perfectly fine.But when I pass "bytesize" or "gsub" it doesn't accept it in the //Something code part.It thinks that "gsub" is not part of the instance methods of "String" which is not true because when I type this in irb: 可以说我通过了“ length”或“ reverse”,并检查了“ String”类,它们工作得很好。但是当我通过“ bytesize”或“ gsub”时,它在/中不接受/某些代码部分。它认为“ gsub”不是“ String”的实例方法的一部分,这是不正确的,因为当我在irb中键入此代码时:

"String".class.instance_methods.include?("gsub".to_sym)

it returns true . 它返回true Can you give an advice ? 你能给个建议吗?

I am not sure what might be the problem, but I imagine there might be something wrong with your @myObject . 我不确定可能是什么问题,但是我想您的@myObject可能有问题。 Verify that it is actually a String object. 验证它实际上是一个String对象。


Some methods of interest that might make the code cleaner. 一些使代码更整洁的令人感兴趣的方法。

method_defined?

>>> String.method_defined? :gsub
true
>>> String.method_defined? :blah
false

respond_to? may be useful as well 可能也有用

myObj = "Test"

>>>myObj.class.method_defined? :gsub
true
>>>myObj.class.method_defined? :blah
false

>>>myObj.respond_to? :gsub
true
>>>myObj.respond_to? :blah
false

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

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