Module: Vector2d::Coercions

Included in:
Vector2d
Defined in:
lib/vector2d/coercions.rb

Instance Method Summary collapse

Instance Method Details

#coerce(other) ⇒ Object



5
6
7
8
9
10
11
12
13
14
# File 'lib/vector2d/coercions.rb', line 5

def coerce(other)
  case other
  when Vector2d
    [other, self]
  when Array, Numeric, String, Hash
    [Vector2d.parse(other), self]
  else
    raise TypeError, "#{self.class} can't be coerced into #{other.class}"
  end
end

#inspectObject

Renders vector as a pretty string.

Vector2d(2, 3).inspect # => "Vector2d(2,3)"


20
21
22
# File 'lib/vector2d/coercions.rb', line 20

def inspect
  "Vector2d(#{x},#{y})"
end

#to_aObject

Converts vector to array.

Vector2d(2, 3).to_a # => [2,3]


28
29
30
# File 'lib/vector2d/coercions.rb', line 28

def to_a
  [x, y]
end

#to_f_vectorObject

Converts vector to floats.

Vector2d(2, 3).to_f_vector # => Vector2d(2.0,3.0)


52
53
54
# File 'lib/vector2d/coercions.rb', line 52

def to_f_vector
  self.class.new(x.to_f, y.to_f)
end

#to_hashObject

Converts vector to hash.

Vector2d(2, 3).to_hash # => {x: 2, y: 3}


36
37
38
# File 'lib/vector2d/coercions.rb', line 36

def to_hash
  { x: x, y: y }
end

#to_i_vectorObject

Converts vector to fixnums.

Vector2d(2.0, 3.0).to_i_vector # => Vector2d(2,3)


44
45
46
# File 'lib/vector2d/coercions.rb', line 44

def to_i_vector
  self.class.new(x.to_i, y.to_i)
end

#to_sObject

Converts vector to string.

Vector2d.new(150, 100).to_s # => "150x100"


60
61
62
# File 'lib/vector2d/coercions.rb', line 60

def to_s
  "#{x}x#{y}"
end