簡體   English   中英

'initialize':錯誤的參數數量(給定3個,預期為0)(ArgumentError)

[英]`initialize': wrong number of arguments (given 3, expected 0) (ArgumentError)

我有以下代碼:

load 'Point.rb'
class Triangle

    def initialize(x, y , z)
        if !x.is_a?(Point) || !y.is_a?(Point) || !z.is_a?(Point)
            puts "Invalid data, a Triangle can only be initialized through points"
        else
            @x=x
            @y=y
            @z=z
            @type=type(x, y, z)
        end
    end

    def type(x, y, z)
        if x.distance(y) == y.distance(z) && y.distance(z) == z.distance(x)
            return "equilateral"
        elsif x.distance(y)== y.distance(z) || y.distance(z) == z.distance(x) || z.distance(x) == x.distance(y)
            return "isosceles"
        else
            return "scalene"
        end
    end

    attr_accessor :type
end

我正在這樣調用方法:

load 'Triangle.rb'

x=Point.new(0,0)
y=Point.new(1,1)
z=Point.new(2,0)
triangle=Triangle.new x, y, z
puts triangle.type

Point如下:

class Point

    def initialize (x=0, y=0)
        @x=x.to_i
        @y=y.to_i
    end

    def ==(point)
        if @x==point.x && @y==point.y
            return true
        else
            return false
        end
    end

    def distance(point)
        Math.hypot((@x-point.x),(@y-point.y))
    end

    attr_accessor :y
    attr_accessor :x
end

錯誤如下:

Triangle.rb:11:in `initialize': wrong number of arguments (given 3, expected 0) (ArgumentError)
    from Triangle_test.rb:6:in `new'
    from Triangle_test.rb:6:in `<main>'

請告訴我們整個代碼是否只是垃圾。

在您的Triangle類中,您有一個接受三個參數的方法type ,然后在下面有attr_accessor :type ,它用無參數的吸氣劑覆蓋了3參數方法。

這就是為什么在初始化程序中出現此錯誤的原因

@type=type(x, y, z)

這是代碼的清理版本:

  • 如果不需要,將其刪除
  • 刪除了不必要的退貨
  • 定義了一個私人的calculate_type方法
  • attr_accessor替換為attr_reader
  • a,b,c重命名x,y,z以避免坐標和點之間的混淆

class Point
  attr_reader :x, :y
  def initialize(x = 0, y = 0)
    @x = x.to_i
    @y = y.to_i
  end

  def ==(point)
    @x == point.x && @y == point.y
  end

  def distance(point)
    Math.hypot((@x - point.x), (@y - point.y))
  end
end

class Triangle
  attr_reader :a, :b, :c, :type

  def initialize(a, b, c)
    raise 'Invalid data, a Triangle can only be initialized through points' unless [a, b, c].all? { |p| p.is_a?(Point) }
    @a, @b, @c = a, b, c
    @type = calculate_type
  end

  private

  def calculate_type
    if a.distance(b) == b.distance(c) && b.distance(c) == c.distance(a)
      'equilateral'
    elsif a.distance(b) == b.distance(c) || b.distance(c) == c.distance(a) || c.distance(a) == a.distance(b)
      'isosceles'
    else
      'scalene'
    end
  end
end

a = Point.new(0, 0)
b = Point.new(1, 1)
c = Point.new(2, 0)
triangle = Triangle.new a, b, c
puts triangle.type
# isosceles

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM