Ruby初学者课题

tsh*_*uck 0 ruby class

在我开始使用rails dev之前,我正在尝试更深入地学习ruby,但是我在学习课程时遇到了一些问题.我似乎无法理解为什么以下不起作用.

#point.rb
class Point
  attr_accessor :x, :y

  def initialize(p = [0,0])
   @x = p[0]
   @y = p[1]
  end
end

#shape.rb
require_relative 'point.rb'

class Shape

  attr_accessor :points

  def initialize *the_points
    for p in the_points
      @points.append Point.new(p)
    end
  end

end

s = Shape.new([3,2])

puts s.points
Run Code Online (Sandbox Code Playgroud)

当我调用该函数时,我得到NilClass的no方法错误,我假设它是指@ point.append.

rmk*_*rmk 5

首先,试试这个:

def initialize *the_points
  @points = []
  for p in the_points
    @points << Point.new(p)
  end
end
Run Code Online (Sandbox Code Playgroud)

你得到NilClass错误是因为@points实例变量是Nil,而NilClass没有append()方法.