tags:

views:

626

answers:

5

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]
+4  A: 

Or if you want arbitrary dimension behavior of that variety (like mathematical vector addition)

 class Vector < Array
   def +(other)
     case other
     when Array
       raise "Incorrect Dimensions" unless self.size == other.size
       other = other.dup
       self.class.new(map{|i| i + other.shift})
     else
       super
     end
   end
 end

class Array
  def to_vector
    Vector.new(self)
  end
end 

[100,100].to_vector + [2,3] #=> [102,103]

The lack of a lisp style map is quite obnoxious.

Ben Hughes
+5  A: 

Array#zip:

$ irb
irb(main):001:0> [100,100].zip([2,3]).map{ |e| e.first + e.last }
=> [102, 103]
Martin Carpenter
+1  A: 
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
Chuck
Great use of modules, but having some instances of Array interpret the + operator in a different way than other instances really scares me. You might even get situations where (a + b) != (b + a).
molf
+11  A: 

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]
Sinan Ünür
+3  A: 

When in Rome..monkeypatch.

module Enumerable
  def sum
    inject &:+
  end

  def vector_add(*others)
    zip(*others).collect &:sum
  end
end

Then you can do a.vector_add(b) and it works. I believe this requires Ruby 1.8.7, or an extension that adds Symbol.to_proc. You can also add an arbitrary number of vectors this way.

stephenjudkins