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]
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
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.
module PixelAddition
def +(other)
zip(other).map {|num| num[0]+num[1]}
end
end
Then you can either create an Array subclass that mixes in the module, or add the behavior to specific arrays like:
class <<an_array
include PixelAddition
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With