写一个比较点方法

时间:2011-10-03 11:15:39

标签: ruby methods compare point

我试图写一个比较点值,例如1,0等于1,0(真) 这就是我到目前为止所拥有的。 任何想法?

class Point 

attr_reader :x, :y


    def initialize x,y
    @x =x
    @y =y
    end


def compare_point(x,y , a,b)   # used to compare points 

 if(x=a, y=b)

puts correct

else
puts wrong

 end
end

end


@current_location = Point.new 1,0


@start_location = Point.new 1,0

compare_point(@start_location,@current_location)

1 个答案:

答案 0 :(得分:3)

class Point
  attr_reader :x, :y

  def initialize(x, y)
    @x = x
    @y = y
  end

  def ==(another)
    [x, y] == [another.x, another.y]
  end
end

Point.new(1, 1) == Point.new(1, 1) #=> true
Point.new(1, 1) == Point.new(2, 1) #=> false

请注意,如果您使用Struct,则可以免费获得访问者和相等性:

class Point < Struct.new(:x, :y)
  # other methods here
end