Ruby 中未定义的方法错误
下面的例子是我的教授在课堂上展示的,它工作得很好并且打印出来,
def printv(g)
puts g.call("Fred")
puts g.call("Amber")
end
printv(method(:hello))
>>hello Fred
hello Amber
但是当我尝试在我的 irb/RubyMine 上运行它时,它显示了未定义的方法错误。我正在尝试他在课堂上展示的确切代码。我缺少什么?
谢谢!
The following example was showed by my professor in class and it worked perfectly fine and printed
def printv(g)
puts g.call("Fred")
puts g.call("Amber")
end
printv(method(:hello))
>>hello Fred
hello Amber
but when I am trying to run it on my irb/RubyMine its showing undefined method error. I am trying the exact code what he showed in class. What am I missing?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您查看
printv
的代码,您会发现g
必须提供一个call
方法。 Ruby 中有几个类默认提供call
方法,其中包括 procs 和 lambda:这里
hello
是一个存储 lambda 的变量,因此您不需要符号 (:hello
) 来引用它。现在让我们看看方法
method
。根据文档,它“将命名方法查找为 obj 中的接收者,返回 Method 对象(或引发 NameError)”。它的签名是“obj.method(sym) → method”,这意味着它接受一个符号参数并返回一个 方法对象。如果您现在调用method(:hello)
,您将收到文档中提到的NameError
,因为当前没有名为“hello”的方法。一旦您定义了一个,事情就会起作用:这也解释了为什么您在对另一个答案的评论中提到的调用
printv(method("hello")
失败:method< /code> 尝试提取方法对象,但如果没有该名称的方法,则会失败(顺便说一句,字符串作为参数似乎可以工作,似乎
method
会实习生其参数以防万一)。If you look at the code for
printv
, you'll see thatg
will have to provide acall
method. There are several classes in Ruby that provide acall
method by default, amongst them procs and lambdas:Here
hello
is a variable storing a lambda, so you don't need a symbol (:hello
) to reference it.Now let's look at the method
method
. According to the docs it "[l]ooks up the named method as a receiver in obj, returning a Method object (or raising NameError)". It's signature is "obj.method(sym) → method", meaning it takes a symbol argument and returns a method object. If you callmethod(:hello)
now, you'll get theNameError
mentioned in the docs, since there is currently no method named "hello". As soon as you define one, things will work though:This also explains why the call
printv(method("hello")
that you mention in your comment on the other answer fails:method
tries to extract a method object, but fails if there is no method by that name (a string as argument seems to work by the way, seems likemethod
interns its argument just in case).您还需要定义方法“hello”。
You'll need to define the method "hello" as well.