Ruby:调用 3:Fixnum 的私有方法
我正在尝试了解这个简单函数的细微差别,但不确定我需要做什么来修复这个 NoMethodError。如何将“分割”公开而不是私有?这能解决问题吗?
这是我的代码:
DATA = [3, 4, 5, 6, 7, 8]
DATA.each do |line|
vals = line.split
print vals[0] + vals[1], " "
end
这是在 IRB 中运行此代码时收到的错误消息:
NoMethodError: private method `split' called for 3:Fixnum
I am trying to learn the nuances of this simple function but am not sure what I need to do to fix this NoMethodError. How do I make 'split' public rather than private? Will that fix the problem?
Here is my code:
DATA = [3, 4, 5, 6, 7, 8]
DATA.each do |line|
vals = line.split
print vals[0] + vals[1], " "
end
Here is the error message I get when I run this in IRB:
NoMethodError: private method `split' called for 3:Fixnum
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
目前尚不清楚你想做什么。您没有“行”,您有一个 Array 中的元素,它是一个 Integer 值。
Split
是在String 上定义的方法。
现在,您收到令人困惑的错误消息的原因有点有趣。碰巧的是,有一个
Kernel#split
可以让脚本变得像 Perl 一样简洁。它拆分全局变量$_
,该变量保存gets
的最后结果。但是混合到对象中,因此它可以在脚本级别使用,留下的问题是创建的每个类最终都会有一个
#split
方法。如果您运行普通的旧 split() 系统中的每个对象都会响应,但幸运的是只会出现错误。
通过使其成为私有方法,它可以在脚本的顶层使用(因为“对象”是开放的或者其他什么),但最终不会成为每个实例化对象的API的一部分。
It's not clear what you are trying to do. You don't have a "line", you have an element from the Array that is an Integer value.
Split
is a method defined onString.
Now, the reason you get that confusing error message is a little bit interesting. As it happens, there is a
Kernel#split
which allows a Perl-like brevity for scripts. It splits the global variable$_
which holds the last result fromgets
.But being mixed in to Object, so it is available at the script level, leaves the problem that every single class ever created ends up having a
#split
method.If you run plain old split() every object in the system will respond, but fortunately only with an error.
By making it a private method, it's available at the top level for scripts (because "Object" is open or something) but doesn't end up part of the API of every single instantiated object.
您正在对数字对象调用方法
split
- 此方法存在于String
类中,但不存在于Fixnum
中。我认为你想要做的是:
You are calling the method
split
on a number object — this method exists in theString
class but not inFixnum
.I think what you're trying to do is this:
猜测您可能真正想要什么:
编辑:基于对连续对进行操作的愿望:
Guessing at what you might really want:
Edit: Based on the desire to operate on successive pairs: