Ruby:调用3:Fixnum的私有方法

问题描述:

我正在尝试学习此简单功能的细微差别,但不确定如何解决此NoMethodError问题.如何将拆分"设置为公开而非私有?这样可以解决问题吗?

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?

这是我的代码:

DATA = [3, 4, 5, 6, 7, 8]
DATA.each do |line|
vals = line.split
print vals[0] + vals[1], " "
end

这是我在IRB中运行此错误消息:

Here is the error message I get when I run this in IRB:

NoMethodError: private method `split' called for 3:Fixnum

您正在数字对象上调用方法split-该方法存在于String类中,但不存在于Fixnum中.

You are calling the method split on a number object — this method exists in the String class but not in Fixnum.

我认为您要这样做的是

DATA = ['3,4', '5,6', '7,8']
DATA.each do |val|
  vals = line.split ','
  print vals[0] + vals[1], " "
end