How do I perform vector addition in Ruby?

ruby

Solution

See the Vector class:

require "matrix"

x = Vector[100, 100]
y = Vector[2, 3]
print x + y

E:\Home> ruby t.rb
Vector[102, 103]

See vectorops for additional operations on vectors:

… the following operations work like expected

  v1 = Vector[1,1,1,0,0,0]
  v2 = Vector[1,1,1,1,1,1]

  v1[0..3]
  # -> Vector[1,1,1]

  v1 += v2
  # -> v1 == Vector[2,2,2,1,1,1]

  v1[0..3] += v2[0..3]
  # -> v1 == Vector[2,2,2,0,0,0]

  v1 + 2
  # -> Vector[3,3,3,1,1,1]

See also vectorops.

Note that matrix is no longer a default gem starting with Ruby 3.1.0. Thanks to Dan Murphy for mentioning this.

Problem

How do I perform vector addition in Ruby so that ``` [100, 100] + [2, 3] ``` yields ``` [102, 103] ``` (instead of joining two arrays)? Or it can be another operator too, such as ``` [100, 100] @ [2, 3] ``` or ``` [100, 100] & [2, 3] ```

Original source

Related problems