# Assignment operator on Vector

Discussion in 'Ruby' started by Hans Sjunnesson, Jan 19, 2006.

1. ### Hans SjunnessonGuest

I'm fairly new to Ruby and I've just come across something I find odd.
I can't seem to assign a value to an element of a Vector.

The following snippet:

require 'matrix'
v = Vector[10, 20, 30]
v[0] = 30

Will give a NoMethodError exception like so:
NoMethodError: undefined method `[]=' for Vector[10, 20, 30]:Vector
from (irb):3

So, is this intentional design? Is the idea to use Arrays when you want
to modify initial elements?

--
Hans Sjunnesson

Hans Sjunnesson, Jan 19, 2006

2. ### Robert KlemmeGuest

Hans Sjunnesson wrote:
> I'm fairly new to Ruby and I've just come across something I find odd.
> I can't seem to assign a value to an element of a Vector.
>
> The following snippet:
>
> require 'matrix'
> v = Vector[10, 20, 30]
> v[0] = 30
>
> Will give a NoMethodError exception like so:
> NoMethodError: undefined method `[]=' for Vector[10, 20, 30]:Vector
> from (irb):3
>
> So, is this intentional design?

I guess Vector is meant as an immutable class. If you check the interface
doc at http://www.ruby-doc.org/stdlib/libdoc/matrix/rdoc/index.html it
states that Vector represents a mathematical vector - and there are no
modifying methods. But you can do math with them:

>> Vector[1,2,3,4] + Vector[0,0,10,0]

=> Vector[1, 2, 13, 4]

This is a new object.

> Is the idea to use Arrays when you
> want to modify initial elements?

If you don't want to do math then sticking with Array is probably the best
solution. Btw, what do you mean by "initial elements"?

Kind regards

robert

Robert Klemme, Jan 19, 2006