Class: RubyVor::Point

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_vor/point.rb,
ext/ruby_vor_c.c

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(x = 0.0, y = 0.0) ⇒ Point

Returns a new instance of Point.

Raises:

  • (TypeError)


4
5
6
7
8
# File 'lib/ruby_vor/point.rb', line 4

def initialize(x=0.0,y=0.0)
  raise TypeError, 'Must be able to convert point values into floats' unless x.respond_to?(:to_f) && y.respond_to?(:to_f)
  @x = x.to_f
  @y = y.to_f
end

Instance Attribute Details

#xObject (readonly)

Returns the value of attribute x.



3
4
5
# File 'lib/ruby_vor/point.rb', line 3

def x
  @x
end

#yObject (readonly)

Returns the value of attribute y.



3
4
5
# File 'lib/ruby_vor/point.rb', line 3

def y
  @y
end

Instance Method Details

#<(p) ⇒ Object



14
15
16
# File 'lib/ruby_vor/point.rb', line 14

def <(p)
  (self <=> p) == -1
end

#<=>(p) ⇒ Object



10
11
12
# File 'lib/ruby_vor/point.rb', line 10

def <=>(p)
  (@x != p.x) ? @x <=> p.x : @y <=> p.y
end

#==(p) ⇒ Object Also known as: eql?



22
23
24
# File 'lib/ruby_vor/point.rb', line 22

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

#>(p) ⇒ Object



18
19
20
# File 'lib/ruby_vor/point.rb', line 18

def >(p)
  (self <=> p) == 1
end

#distance_from(other) ⇒ Object

Euclidean distance between two Points



9
10
11
12
13
14
# File 'ext/rb_cPoint.c', line 9

VALUE
RubyVor_distance_from(VALUE self, VALUE other)
{
    return rb_float_new(sqrt(pow(NUM2DBL(rb_iv_get(self, "@x")) - NUM2DBL(rb_iv_get(other, "@x")), 2.0) +
                             pow(NUM2DBL(rb_iv_get(self, "@y")) - NUM2DBL(rb_iv_get(other, "@y")), 2.0)));
}

#hashObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'ext/rb_cPoint.c', line 16

VALUE
RubyVor_point_hash(VALUE self)
{
    double x, y;
    char *c;
    long i, xHash, yHash;

    x = NUM2DBL(rb_iv_get(self, "@x"));
    y = NUM2DBL(rb_iv_get(self, "@y"));

    /* Bastardized from Ruby's numeric.c */
    
    for (c = (char*)&x, xHash = 0, i = 0; i < sizeof(double); i++) xHash += c[i] * 971;
    for (c = (char*)&y, yHash = 0, i = 0; i < sizeof(double); i++) yHash += c[i] * 971;

    xHash = xHash & RB_HASH_FILTER;
    yHash = yHash & RB_HASH_FILTER;
    
    return LONG2FIX((xHash << (RB_LONG_BITS / 2)) | yHash);
}

#to_sObject



27
28
29
# File 'lib/ruby_vor/point.rb', line 27

def to_s
  "(#{@x},#{@y})"
end